classmethod
개체는 설명자입니다. 설명 자의 작동 방식을 이해해야합니다. self
, instance
및 instance type
: 요컨대
는 디스크립터는 세 개의 인자를 취하는 방법
__get__
을 갖는 것을 목적으로한다.
일반적인 특성 조회 중에 조회 된 개체 A
에 __get__
메서드가 있으면 해당 메서드가 호출되고 반환되는 개체는 A
개체로 대체됩니다. 이것은 함수 (descriptors)가 객체의 메소드를 호출 할 때 바운드 메소드가되는 방식입니다.
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'
"누락 된"__name__에 대한 통찰력은 없지만 classmethods에는 '__call__'래퍼가 있는지 확인해야합니다. – mjv