標籤:通過 item getattr log hello 根據 nbsp 成員 索引值
常見內建函數
內建函數:在類的內部,特定時機自動觸發的函數
樣本1:setattr、getattr、delattr
class Person: # def __init__(self, name): # self.name = name? def __setattr__(self, key, value): # 當設定對象成員屬性的時,系統會自動調用 print(key, value) self.__dict__[key] = value? def __getattr__(self, item): # 當訪問不存在的對象屬性時,系統會自動調用 if item == ‘age‘: return 123 else: return ‘default‘? def __delattr__(self, item): # 當銷毀對象的成員屬性時,系統會自動調用 print(‘del‘, item)xiaoming = Person()
每個對象都有一個成員屬性:dict 用於存放對象的屬性,包括動態添加的
print(xiaoming.dict)xiaoming.name = ‘小明‘print(xiaoming.name)print(xiaoming.dict)xiaoming.age = 18print(xiaoming.age) print(xiaoming.hello)del xiaoming.age
樣本2:setitem、getitem、delitem
當對對象按照字典方式操作時,會自動觸發相關方法
樣本:
class Person: # 當對對象按照字典設定索引值對時,會自動觸發該方法 def __setitem__(self, key, value): # print(key, value) self.__dict__[key] = value? # 當對對象按照字典操作根據鍵擷取值時,會自動觸發該方法 def __getitem__(self, item): # print(item) return self.__dict__[item]? # 當做字典操作,刪除索引值對時,自動觸發該方法 def __delitem__(self, key): # print(key) del self.__dict__[key] p = Person()p[‘name‘] = ‘xiaoming‘print(p[‘name‘])?# 通過字典方式添加的索引值對,可以通過屬性的方式擷取print(p.name)print(p.dict)del p[‘name‘]
python 常見內建函數setattr、getattr、delattr、setitem、getitem、delitem