Inconsistency of special class method lookup?

G

Guest

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)
 
P

Peter Otten

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,584
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top