問題涉及到哪一個更好用用於哪個用例,而不是關於技術背景。用例屬性與描述符vs. __getattribute__
在Python中,你可以控制通過財產,一個描述,或魔術方法屬性的訪問。在哪個用例中哪一個是最pythonic?它們都似乎具有相同的效果(請參閱下面的示例)。
我正在尋找像一個答案:
- 物業:應在以下情況下可使用...
- 描述:在... ...的情況下,它應該被用來代替屬性。
- 不可思議的方法:只有在...時使用。
例
用例將是可能無法在__init__
方法進行設置,例如,因爲該對象不存在於數據庫又一個屬性,但在稍後的時間。每次訪問屬性時,都應嘗試設置並返回。
作爲一個適用於複製&粘貼到Python shell的示例,有一個類只在第二次請求它時才顯示其屬性。那麼,哪一個纔是最好的方式,還是有不同的情況,其中一個更可取?這裏有三種方式實現:
隨着物業 ::
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 H的一個它有這種行爲::
book = ContactBook()
print(book.first_person)
# >>None
print(book.first_person)
# >>Mr. First
'__getattribute__'是**總是被調用,'__getattr__'只會在沒有通過其他方式找到屬性時被調用。 '__getattribute__'是'property'(和其他描述符對象)完成工作的機制。 –
這是一個_descriptor_不是_decorator_ – Eric
@Eric:謝謝,我編輯了這個問題。 – Iodnas