我想知道在元类上声明的方法会发生什么。我预计如果你在元类上声明一个方法,它最终会成为一个类方法,但是,行为是不同的。例子
>>> class A(object):
... @classmethod
... def foo(cls):
... print "foo"
...
>>> a=A()
>>> a.foo()
foo
>>> A.foo()
foo
但是,如果我尝试定义一个元类并给它一个方法 foo,它似乎对类起作用,而不是对实例起作用。
>>> class Meta(type):
... def foo(self):
... print "foo"
...
>>> class A(object):
... __metaclass__=Meta
... def __init__(self):
... print "hello"
...
>>>
>>> a=A()
hello
>>> A.foo()
foo
>>> a.foo()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'A' object has no attribute 'foo'
这里到底发生了什么?
编辑:碰到问题