classmethod 对象是一个描述符。您需要了解描述符的工作原理。
简而言之,描述符是具有__get__ 方法的对象,该方法接受三个参数:self、instance 和instance type。
在普通属性查找期间,如果查找的对象A 具有方法__get__,则调用该方法并将其返回的内容替换为对象A。这就是当您在对象上调用方法时,函数(也是描述符)成为绑定方法的方式。
class Foo(object):
def bar(self, arg1, arg2):
print arg1, arg2
foo = Foo()
# this:
foo.bar(1,2) # prints '1 2'
# does about the same thing as this:
Foo.__dict__['bar'].__get__(foo, type(foo))(1,2) # prints '1 2'
classmethod 对象的工作方式相同。当它被查找时,它的__get__ 方法被调用。类方法的__get__ 丢弃与instance 对应的参数(如果有的话),并且仅在它调用包装函数上的__get__ 时传递instance_type。
说明性涂鸦:
In [14]: def foo(cls):
....: print cls
....:
In [15]: classmethod(foo)
Out[15]: <classmethod object at 0x756e50>
In [16]: cm = classmethod(foo)
In [17]: cm.__get__(None, dict)
Out[17]: <bound method type.foo of <type 'dict'>>
In [18]: cm.__get__(None, dict)()
<type 'dict'>
In [19]: cm.__get__({}, dict)
Out[19]: <bound method type.foo of <type 'dict'>>
In [20]: cm.__get__({}, dict)()
<type 'dict'>
In [21]: cm.__get__("Some bogus unused string", dict)()
<type 'dict'>
有关描述符的更多信息可以在此处(以及其他地方)找到:
http://users.rcn.com/python/download/Descriptor.htm
对于获取由classmethod包裹的函数名称的具体任务:
In [29]: cm.__get__(None, dict).im_func.__name__
Out[29]: 'foo'