Python 元类和对象基类
在阅读了优秀的 SO 帖子后,我尝试制作一个模块level 元类:
def metaclass(future_class_name, future_class_parents, future_class_attrs):
print "module.__metaclass__"
future_class_attrs["bar"]="bar"
return type(future_class_name, future_class_parents, future_class_attrs)
__metaclass__=metaclass
class Foo(object):
def __init__(self):
print 'Foo.__init__'
f=Foo()
除非我删除 Foo 的 object
基类,否则这不起作用(即“module.metaclass”不会被打印)。怎么会?
注意:我使用的是 Python 2.6.1。
After reading the excellent SO post, I tried crafting a module level metaclass:
def metaclass(future_class_name, future_class_parents, future_class_attrs):
print "module.__metaclass__"
future_class_attrs["bar"]="bar"
return type(future_class_name, future_class_parents, future_class_attrs)
__metaclass__=metaclass
class Foo(object):
def __init__(self):
print 'Foo.__init__'
f=Foo()
This doesn't work (i.e. "module.metaclass" doesn't get printed) unless I remove the object
base class of Foo. How come?
NOTE: I am using Python 2.6.1.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
从object继承会自动带来type元类。这会覆盖您的模块级别 __metaclass__ 规范。
如果在类级别指定元类,则 object 将不会覆盖它:
请参阅 http://docs.python.org/reference/datamodel.html?highlight=元类#customizing-class-creation
Inheriting from object automatically brings the type metaclass along with it. This overrides your module level __metaclass__ specification.
If the metaclass is specified at the class level, then object won't override it:
See http://docs.python.org/reference/datamodel.html?highlight=metaclass#customizing-class-creation
规范 指定 Python 查找元类的顺序:
从上面你会看到,拥有一个基类(无论基类是什么,即使它最终不是从
object
继承)会抢占模块 -级别__metaclass__
。The specification specifies the order in which Python will look for a metaclass:
You will see from the above that having a base class at all (whatever the base class is, even if it does not ultimately inherit from
object
) pre-empts the module-level__metaclass__
.