Question

It's said that :

When it would yield a class method object, it is transformed into a bound user-defined method object whose im_class and im_self attributes are both C.

in the Reference

And I did an EX.

>>> class C(object) :
...     @classmethod
...     def cm(cls) : print cls
... 
>>> C.cm
<bound method type.cm of <class '__main__.C'>>
>>> C.cm.im_self
<class '__main__.C'>
>>> C.cm.im_class
<type 'type'>

It's not hard for me to understand the phenomenon. But unfortunately, in the reference, it's told that im_self should be the same as im_class. How to explain the inconsistency?

Was it helpful?

Solution

I read that the same way you do. It appears that what Python is actually doing is not exactly what the documentation says.

It sets im_self to the class, and im_class to the class's type, i.e., its metaclass. The default metaclass for classes in Python is type. This is analogous to what happens with methods that are bound to instances: im_self is the instance and im_class is the type of the instance. In the case of @classmethod, in other words, the class is treated as the instance (which it is; it's an instance of type).

Possibly the behavior was changed without the documentation being updated, or the documentation was just wrong to begin with. I write documentation for a living and I can confirm that it is almost impossible to keep it 100% correct for something the size of Python -- especially for obscure details like this one.

The Python developers have a procedure for reporting bugs in the documentation. Give it a try!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top