魔法函數 getattr 與 getattribute
簡單說明
__getattr__
與__getattribute__
魔法函數的使用
書上說,天下沒有不散的宴席,不要怕,書上還說了,人生何處不相逢。
——《雪中悍刀行》
__getattr__魔法函數
_getattr_
魔法函數是在你試圖訪問一個不存在的屬性時調用的。
如果沒有這個魔法函數,訪問不存在的屬性程序會報錯。
from datetime import date
class User:
def __init__(self, name, birthday):
self.name = name
self.birthday = birthday
if __name__ == '__main__':
user = User("無夢生7", date(year=1997, month=1, day=1))
print(user.age) # 訪問不存在的屬性
輸出結果如下。
上面程序中我們加入 __getattr__
from datetime import date
class User:
def __init__(self, name, birthday):
self.name = name
self.birthday = birthday
# 查找不到屬性的時候調用
def __getattr__(self, item):
return "not find attr"
if __name__ == '__main__':
user = User("無夢生7", date(year=1997, month=1, day=1))
print(user.age) # 訪問不存在的屬性
輸出結果如下。
作用
- 使用這個函數我們可以加入自己的邏輯處理
- 如返回一個 None,或者打印一些提示內容,或者進行糾正。
- 比如你的屬性都是小寫,對方訪問一個大寫的,你這裏就可以自動轉換成小寫等。
__getattribute__魔法函數
__getattribute__
魔法函數是在 __getattr__
之前執行
- 無論你訪問的屬性是不是存在都返回這個函數裏面的返回值。
- 即無條件優先進入這個魔法函數內,不會先尋找其他屬性。
- 這個方法儘量不要自己重寫,只有在寫框架是會用到此魔法函數。
from datetime import date
class User:
def __init__(self, name, birthday):
self.name = name
self.birthday = birthday
# 查找不到屬性的時候調用
def __getattr__(self, item):
return "not find attr"
def __getattribute__(self, item):
return "無條件優先進入"
if __name__ == '__main__':
user = User("無夢生7", date(year=1997, month=1, day=1))
print(user.age) # 訪問不存在的屬性
輸出結果如下。
總結
-
__getattr__
在查找不到屬性的時候調用,如果沒有這個魔法函數會報錯。 -
__getattribute__
無條件優先進入這個魔法函數內,不會先尋找其他屬性。