I'm having trouble to understand how a classmethod object works in Python, especially in the context of metaclasses and in __new__
. In my special case I would like to get the name of a classmethod member, when I iterate through the members
that were given to __new__
.
For normal methods the name is simply stored in a __name__
attribute, but for a classmethod there is apparently no such attribute. I don't even see how the classmethod is invoked, as there is no __call__
attribute either.
Can someone explain to me how a classmethod works or point me to some documentation? Googling led me nowhere. Thanks!
This looks like it has the goods.
A
classmethod
object is a descriptor. You need to understand how descriptors work.In a nutshell, a descriptor is an object which has a method
__get__
, which takes three arguments:self
, aninstance
, and aninstance type
.During normal attribute lookup, if a looked-up object
A
has a method__get__
, that method gets called and what it returns is substituted in place for the objectA
. This is how functions (which are also descriptors) become bound methods when you call a method on an object.A
classmethod
object works the same way. When it gets looked up, its__get__
method gets called. The__get__
of a classmethod discards the argument corresponding to theinstance
(if there was one) and only passes along theinstance_type
when it calls__get__
on the wrapped function.A illustrative doodle:
More info on descriptors can be found here (among other places): http://users.rcn.com/python/download/Descriptor.htm
For the specific task of getting the name of the function wrapped by a
classmethod
: