Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/305.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
具有自定义元类行为的Python元类_Python_Oop_Metaclass - Fatal编程技术网

具有自定义元类行为的Python元类

具有自定义元类行为的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

我正在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 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调用方法不起作用