Unexpected __metaclass__ method behavior

Terry Reedy tjreedy at udel.edu
Sun Dec 30 18:03:24 EST 2007


<anne.nospam01 at wangnick.de> wrote in message 
news:2273796e-87c6-4100-a5b5-1c6afa32a276 at i29g2000prf.googlegroups.com...
| Dear fellow Pythonians,
|
| I just stumbled upon the following unexpected behavior:
|
| class TestType(type):
|    def Foo(self): return 'TestType Foo'
| class Test(object):
|    __metaclass__ = TestType
|    def Foo(self): return 'Test Foo'
| t = Test()
| print t.Foo()
| print Test.Foo()
|
| This will produce:
| Test Foo
| Traceback (most recent call last):
|  File "test.py", line 8, in <module>
|    print Test.Foo()
| TypeError: unbound method Foo() must be called with Test instance as
| first argument (got nothing instead)
|
| I can imagine why this is happening, and that there is no easy
| solution, but it is not what I was expecting.

Regardless of which Foo you expect to be called, both require an instance 
argument to be bound to the paramenter 'self'.

print Test.Foo(t) # will print same as t.Foo()

tjr






More information about the Python-list mailing list