질문은 을 말합니다. 기술적 인 배경이 아니라을 사용 사례로 사용하는 것이 좋습니다.속성 대 설명자 대 __getattribute__ 사용 사례
파이썬에서, 당신은 재산하는 설명, 또는 마술 방법를 통해 속성의 액세스를 제어 할 수 있습니다. 어느 것이 유스 케이스에서 가장 파이썬 이냐? 그들 모두는 같은 효과를 가지는 것 같습니다 (아래 예 참조). 기술자
- 재산권가 :
내가 좋아하는 대답을 찾고 있어요 ...의 경우 대신 속성으로 사용되어야한다.
- 매직 방법 : 다음 경우에만 사용하십시오.
유스 케이스 개체가 아직 데이터베이스에 존재하지 않기 때문에 예를 들어, __init__
방법에 설정하지 못할 수 있습니다 속성을 것
예,하지만 나중에에서 시각. 속성에 액세스 할 때마다 설정되고 반환되어야합니다.
복사 & Python 셸에 붙여 넣기와 함께 작동하는 예제로서 두 번째로 요청할 때만 속성을 표시하려는 클래스가 있습니다. 그래서, 어느 것이 가장 좋은 방법입니까, 아니면 다른 상황이 있습니까? 그 중 하나가 더 낫습니다. 여기를 구현하는 세 가지 방법은 다음과 같습니다
재산권으로 ::
class ContactBook(object):
intents = 0
def __init__(self):
self.__first_person = None
def get_first_person(self):
ContactBook.intents += 1
if self.__first_person is None:
if ContactBook.intents > 1:
value = 'Mr. First'
self.__first_person = value
else:
return None
return self.__first_person
def set_first_person(self, value):
self.__first_person = value
first_person = property(get_first_person, set_first_person)
__getattribute__
으로 ::
class ContactBook(object):
intents = 0
def __init__(self):
self.first_person = None
def __getattribute__(self, name):
if name == 'first_person' \
and object.__getattribute__(self, name) is None:
ContactBook.intents += 1
if ContactBook.intents > 1:
value = 'Mr. First'
self.first_person = value
else:
value = None
else:
value = object.__getattribute__(self, name)
return value
기술자는 ::
class FirstPerson(object):
def __init__(self, value=None):
self.value = None
def __get__(self, instance, owner):
if self.value is None:
ContactBook.intents += 1
if ContactBook.intents > 1:
self.value = 'Mr. First'
else:
return None
return self.value
class ContactBook(object):
intents = 0
first_person = FirstPerson()
EAC 시간 그 중 하나가이 동작 ::
book = ContactBook()
print(book.first_person)
# >>None
print(book.first_person)
# >>Mr. First
'__getattribute__'은 ** 항상 ** 호출되며, 다른 수단을 통해 속성이 발견되지 않으면'__getattr__' 만 호출됩니다. '__getattribute__'는'property' (및 다른 디스크립터 객체)가 작업을 수행하는 메커니즘입니다. –
그건 _descriptor_ 아니 _decorator_ – Eric
@ 에릭 : 감사합니다, 나는 질문을 편집했습니다. – Iodnas