Why are class methods not classmethods?

S

Steven D'Aprano

There's some subtle behaviour going on here that I don't really follow.
Class methods apparently aren't classmethods.

.... def method(self, *args):
.... return self, args
.... @classmethod
.... def cmethod(cls, *args):
.... return cls, args
....<type 'instancemethod'>


Can anyone explain why class methods bound to a class are instancemethods
rather than classmethods?
 
M

Marc 'BlackJack' Rintsch

Can anyone explain why class methods bound to a class are instancemethods
rather than classmethods?

I'd say because they are bound to the class which is the instance that is
passed as first argument. Just like unbound methods turn into bound
methods when you access them on "normal" objects and change from
functions to instance methods, accessing class methods make them instance
methods too. If you bypass the dot operator you get the still unwrapped
class method:

In [83]: Parrot.cmethod
Out[83]: <bound method type.cmethod of <class '__main__.Parrot'>>

In [84]: type(Parrot.cmethod)
Out[84]: <type 'instancemethod'>

In [85]: Parrot.__dict__['cmethod']
Out[85]: <classmethod object at 0x9b26434>

In [86]: type(Parrot.__dict__['cmethod'])
Out[86]: <type 'classmethod'>

Ciao,
Marc 'BlackJack' Rintsch
 
C

Chris Mellon

There's some subtle behaviour going on here that I don't really follow.
Class methods apparently aren't classmethods.


... def method(self, *args):
... return self, args
... @classmethod
... def cmethod(cls, *args):
... return cls, args
...
<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:

So rather than inventing special machinery for classmethods, Python
uses the existing instancemethod machinery and just changes the object
the instancemethod is bound to.
 

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,769
Messages
2,569,582
Members
45,066
Latest member
VytoKetoReviews

Latest Threads

Top