Why are class methods not classmethods?
Chris Mellon
arkanes at gmail.com
Tue Nov 27 10:53:12 EST 2007
On Nov 27, 2007 3:12 AM, Steven D'Aprano
<steven at remove.this.cybersource.com.au> wrote:
> There's some subtle behaviour going on here that I don't really follow.
> Class methods apparently aren't classmethods.
>
>
> >>> class Parrot(object):
> ... def method(self, *args):
> ... return self, args
> ... @classmethod
> ... def cmethod(cls, *args):
> ... return cls, args
> ...
> >>> type(parrot.method) # as expected
> <type 'instancemethod'>
> >>> type(parrot.cmethod) # I don't expect this result
> <type 'instancemethod'>
> >>> type(classmethod(parrot.method))
> <type 'classmethod'>
> >>>
> >>> parrot.cm = classmethod(parrot.method)
> >>> type(parrot.cm) # I expect this
> <type 'classmethod'>
> >>>
> >>> Parrot.CM = classmethod(parrot.method)
> >>> type(Parrot.CM) # but not this
> <type 'instancemethod'>
>
>
> Can anyone explain why class methods bound to a class are instancemethods
> rather than classmethods?
>
>
They're instancemethods bound to the type instance, rather than to an
instance of the type:
>>> c = C()
>>> c.method
<bound method C.method of <__main__.C object at 0x01B8F330>>
>>> c.cmethod
<bound method type.cmethod of <class '__main__.C'>>
>>>
So rather than inventing special machinery for classmethods, Python
uses the existing instancemethod machinery and just changes the object
the instancemethod is bound to.
More information about the Python-list
mailing list