는 설명을위한 파이썬 만 검사하지 않는 경우에, 클래스에 속성을 찾는 경우 때문에 작동하지 않는 이유에 대한 사용 사례처럼 보인다; 문제의 방법은 다음과 같습니다
인스턴스뿐만 아니라 클래스에 descriptor protocol을 구현하기 위해 클래스에 이러한 메소드를 오버라이드 (override) 할 수 있습니다 :
# do not use in production, example code only, needs more checks
class ClassAllowingInstanceDescriptors(object):
def __delattr__(self, name):
res = self.__dict__.get(name)
for method in ('__get__', '__set__', '__delete__'):
if hasattr(res, method):
# we have a descriptor, use it
res = res.__delete__(name)
break
else:
res = object.__delattr__(self, name)
return res
def __getattribute__(self, *args):
res = object.__getattribute__(self, *args)
for method in ('__get__', '__set__', '__delete__'):
if hasattr(res, method):
# we have a descriptor, call it
res = res.__get__(self, self.__class__)
return res
def __setattr__(self, name, val):
# check if object already exists
res = self.__dict__.get(name)
for method in ('__get__', '__set__', '__delete__'):
if hasattr(res, method):
# we have a descriptor, use it
res = res.__set__(self, val)
break
else:
res = object.__setattr__(self, name, val)
return res
@property
def world(self):
return 'hello!'
상기 클래스는 아래와 같이 사용되는 경우 :
huh = ClassAllowingInstanceDescriptors()
print(huh.world)
huh.uni = 'BIG'
print(huh.uni)
huh.huh = property(lambda *a: 'really?')
print(huh.huh)
print('*' * 50)
try:
del huh.world
except Exception, e:
print(e)
print(huh.world)
print('*' * 50)
try:
del huh.huh
except Exception, e:
print(e)
print(huh.huh)
결과는 :
안녕하십니까!
빅
?
속성을
인사를 삭제할 수 없습니다!
는
는
정말 속성을 삭제할 수 없습니다 ?
왜 MyClass의 다른 서브 클래스를 오버라이드 된 디스크립터와 함께 사용하지 않는가? – KurzedMetal
더 많은 예제를 추가하기 위해 편집되었습니다. 나는 인스턴스 별 디스크립터를 수행 할 수 없다고 생각한다. 나는 __getattr__을 사용하여 그 주위에서 일했다. 그래도 기본 언어 제약 조건을 이해하지 못합니다. –
설명자는 클래스 수준에서만 작동합니다. 죄송합니다. –