一
classmethod
对象是描述符。您需要了解描述符是如何工作的。
简而言之,描述符是一个具有方法的对象
__get__
,采用三个参数:
self
,一个
instance
和一个
instance type
.
在正常属性查找期间,如果查找的对象
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'
一
分类法
对象的工作方式相同。当它被发现时,
第二代
方法被调用。这个
第二代
类方法的方法,丢弃与
实例
(如果有)并且只经过
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
用于获取由
分类法
:
In [29]: cm.__get__(None, dict).im_func.__name__
Out[29]: 'foo'