具有自定义元类行为的Python元类
我正在Python2.7中使用元类。因此,我创建了如下代码:具有自定义元类行为的Python元类,python,oop,metaclass,Python,Oop,Metaclass,我正在Python2.7中使用元类。因此,我创建了如下代码: class M(type): def __new__(meta, name, parents, attrs): print 'In meta new' return super(meta, meta).__new__(meta, name, parents, attrs) def __init__(cls, *args, **kwargs): print 'In met
class M(type):
def __new__(meta, name, parents, attrs):
print 'In meta new'
return super(meta, meta).__new__(meta, name, parents, attrs)
def __init__(cls, *args, **kwargs):
print 'In meta init'
def __call__(cls, *attr, **val):
print 'In meta call'
return super(cls, cls).__new__(cls)
class A(object):
__metaclass__ = M
def __new__(cls):
print 'In class new'
return super(cls, cls).__new__(cls)
def __init__(self):
print 'In object init'
def __call__(self):
print 'In object call'
但输出让我困惑:
A()
In meta new
In meta init
In meta call
不知何故,类方法new和init被重写了,所以解释器跳过它们。有人能解释一下吗
谢谢你的帮助。你打错了super()
。super()
的第一个参数应该是类本身,而不是它的实例
return super(meta, meta).__new__(meta, name, parents, attrs)
应该是
return super(M, meta).__new__(meta, name, parents, attrs)
对于其他super()
调用,依此类推-第一个参数应该是它们所在的类;第二个是实际实例。您调用的super()
不正确。super()
的第一个参数应该是类本身,而不是它的实例
return super(meta, meta).__new__(meta, name, parents, attrs)
应该是
return super(M, meta).__new__(meta, name, parents, attrs)
对于其他
super()
调用,依此类推-第一个参数应该是它们所在的类;第二个是实际的实例。它不起作用,因为我没有使用原始Python机制--cls()
,它保证了\uuuuuuuu新的
和\uuu初始化
方法的自动工作,它被元类\uuu调用
方法覆盖,它不起作用,因为我没有使用原始Python机制--cls()
,它保证了\uuuuu新的
和\uuuu初始化方法的自动工作,它被元类\uuuu调用方法覆盖,而元类\uuuuuuuu调用方法不起作用