methods of metaclasses on class instances.

Posted by Stefano Borini on Stack Overflow See other posts from Stack Overflow or by Stefano Borini
Published on 2010-02-11T06:37:39Z Indexed on 2010/04/24 12:13 UTC
Read the original article Hit count: 258

Filed under:
|

I was wondering what happens to methods declared on a metaclass. I expected that if you declare a method on a metaclass, it will end up being a classmethod, however, the behavior is different. Example

>>> class A(object):
...     @classmethod
...     def foo(cls):
...         print "foo"
... 
>>> a=A()
>>> a.foo()
foo
>>> A.foo()
foo

However, if I try to define a metaclass and give it a method foo, it seems to work the same for the class, not for the instance.

>>> 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'

What's going on here exactly ?

edit: bumping the question

© Stack Overflow or respective owner

Related posts about python

Related posts about metaclass