Inconsistency of special class method lookup?

Peter Otten __peter__ at web.de
Sat Mar 11 05:32:00 EST 2006


anne.nospam01 at wangnick.de wrote:

> class Foo(object):
>         def __len__(): return 2
>         __len__ = staticmethod(__len__)
> print len(Foo)
> >>>
> Traceback (most recent call last):
>   File "C:/Dokumente und Einstellungen/All Users/Dokumente/foo.py",
> line 4, in ?
>     print len(Foo)
> TypeError: len() of unsized object
> 
> However, the following works:
> 
> class FooType(type):
>         def __len__(self): return self.l()
> class Foo(object):
>         __metaclass__ = FooType
>         def l(): return 3
>         l = staticmethod(l)
> print len(Foo)
> >>>
> 3
> 
> Any good reason why the lookup process doesn't find __len__ as
> staticmethod of the class?

Special methods of newstyle objects are always looked up in the class, and
the class of a class is its metaclass. Therefore 

len(Foo()) invokes type(Foo()).__len__ which is the same as Foo.__len__

and

len(Foo) invokes type(Foo).__len__ which (in your example) is the same as
FooType.__len__.


Peter



More information about the Python-list mailing list