설명자/데코레이터를 중첩하려고 할 때 어떤 일이 발생하는지 이해하는 데 어려움을 겪고 있습니다. 파이썬 2.7 사용하고 있습니다.파이썬에서 중첩 디스크립터/데코레이터
예를 들어, property
및 classmethod
다음과 같은 단순화 된 버전을 보자 :
class MyProperty(object):
def __init__(self, fget):
self.fget = fget
def __get__(self, obj, objtype=None):
print 'IN MyProperty.__get__'
return self.fget(obj)
class MyClassMethod(object):
def __init__(self, f):
self.f = f
def __get__(self, obj, objtype=None):
print 'IN MyClassMethod.__get__'
def f(*args, **kwargs):
return self.f(objtype, *args, **kwargs)
return f
이 둥지를 시도 :
class A(object):
# doesn't work:
@MyProperty
@MyClassMethod
def klsproperty(cls):
return 555
# works:
@MyProperty
def prop(self):
return 111
# works:
@MyClassMethod
def klsmethod(cls, x):
return x**2
% print A.klsproperty
IN MyProperty.__get__
...
TypeError: 'MyClassMethod' object is not callable
내부 설명 MyClassMethod
의 __get__
메소드가 호출 받고 있지 않습니다.
class B(object):
# works:
@NoopDescriptor
@MyProperty
def prop1(self):
return 888
# doesn't work:
@MyProperty
@NoopDescriptor
def prop2(self):
return 999
% print B().prop1
IN NoopDescriptor.__get__
IN MyProperty.__get__
888
% print B().prop2
IN MyProperty.__get__
...
TypeError: 'NoopDescriptor' object is not callable
: 중첩의 무 조작 기술자/장식을 사용하려고
class NoopDescriptor(object):
def __init__(self, f):
self.f = f
def __get__(self, obj, objtype=None):
print 'IN NoopDescriptor.__get__'
return self.f.__get__(obj, objtype=objtype)
: 나는 (내가 무슨 생각) 무 조작 기술자를 던지려고하는 이유 는 파악하지 못하면 왜 B().prop1
이 작동하고 B().prop2
을 이해하지 못합니다.
질문 : 내가 잘못 뭐하는 거지
- ?
object is not callable
오류가 발생하는 이유는 무엇입니까? - 올바른 방법은 무엇입니까? 예 : 데코레이터는 장식이 그것로 꾸미는 기능 호출 매개 변수없이 사용될 때
MyClassMethod
및MyProperty
(또는classmethod
및property
)이 경우
직관적으로 이해하는 열쇠는'@ MyProperty'가 메소드가 아닌 _data_ 속성처럼 작동하는 것을 생성하므로 메소드 설명자로 중첩 할 수 없습니다. 그 직관적 인 이해는 당신을 지금까지만 도달시킵니다. 전체 기사는 isedev의 답변에 있습니다. – abarnert