469,271 Members | 1,466 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,271 developers. It's quick & easy.

Inconsistency of special class method lookup?

Folks,

I'm running into the following issue. A staticmethod of a class seems
not to be accepted as a special class method of the class object
itself. For example:

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?

Regards,
Sebastian (posting using the account of my wife)

Mar 11 '06 #1
2 946
an***********@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
Mar 11 '06 #2
Thanks.

Mar 11 '06 #3

This discussion thread is closed

Replies have been disabled for this discussion.

By using this site, you agree to our Privacy Policy and Terms of Use.