Python類中方法getitem和getattr詳解
阿新 • • 發佈:2020-01-09
1、getitem 方法
使用這個方法最大的印象就是呼叫物件的屬性可以像字典取值一樣使用中括號['key']
使用中括號對物件中的屬性進行取值、賦值或者刪除時,會自動觸發對應的__getitem__、__setitem__、__delitem__方法
程式碼如下:
class Foo(object): def __init__(self): self.name = 'jack' def __getitem__(self,item): if item in self.__dict__: # item = key,判斷該key是否存在物件的 __dict__ 裡, return self.__dict__[item] # 返回該物件 __dict__ 裡key對應的value def __setitem__(self,key,value): self.__dict__[key] = value # 在物件 __dict__ 為指定的key設定value def __delitem__(self,key): del self.__dict__[key] # 在物件 __dict__ 裡刪除指定的key f1 = Foo() print(f1['name']) # jack f1['age'] =10 print(f1['age']) # 10 del f1['name'] print(f1.__dict__) # {'age': 10}
2、getattr 方法
使用物件取值、賦值或者刪除時,會預設的呼叫對應的__getattr__、__setattr__、__delattr__方法。
物件取值時,取值的順序為:先從object裡__getattribute__中找,第二步從物件的屬性中找,第三步從當前類中找,第四步從父類中找,第五步從__getattr__中找,如果沒有,直接丟擲異常。
程式碼如下:
class Foo(object): def __init__(self): self.name = 'jack' def __getattr__(self,item): if item in self.__dict__: return self.__dict__[item] def __setattr__(self,value): self.__dict__[key] = value def __delattr__(self,item): del self.__dict__[item] c1 = Foo() print(c1.name) # jack c1.age = 18 print(c1.age) # 18 del c1.age # 刪除 物件c1的age print(c1.age) # None
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。