標籤:賦值 全域 反射機制 end time after turn size 根據
python中的反射功能是由以下四個內建函數提供:hasattr、getattr、setattr、delattr,改四個函數分別用於對對象內部執行:檢查是否含有某成員、擷取成員、設定成員、刪除成員。
# commons.py 檔案 name = "nick" def f1(): return "This is f1." def f2(): return "This is f2." def nb(): return "This is niubily." # index.py 檔案import commons #根據字串的形式去某個模組中尋找東西target_func = getattr(commons,"f1") # 找函數result = target_func()print(result) target_func = getattr(commons,"name") # 找全域變數print(target_func) target_func = getattr(commons,"age",None) # 找不到返回Noneprint(target_func) #根據字串的形式去某個模組中判斷東西是否存在tarhas_func = hasattr(commons,"f5") # 找函數print("before:",tarhas_func) # tarhas_func = hasattr(commons,"name") # 找全域變數# print(tarhas_func) #根據字串的形式去某個模組中設定東西setattr(commons,"f5","lambda x: return \"This is new func.\"") # 設定一個函數setattr(commons,"age",18) # 設定全域變數 tarhas_func = hasattr(commons,"f5") # 檢查函數是否存在print("after:",tarhas_func) #根據字串的形式去某個模組中刪除東西delattr(commons,"f5") # 刪除一個函數 tarhas_func = hasattr(commons,"f5") # 檢查函數是否存在print("end:",tarhas_func)
對象執行個體
class Foo: def __init__(self,name,age): self.name=name self.age=age def show(self): print("擷取到了該函數方法")obj=Foo(‘2018世界盃‘,2018) #hasattr 是否存在欄位print(hasattr(obj,‘name‘))#getattr擷取資訊getname=getattr(obj,‘name‘)print(getname)#setattr賦值setattr(obj,‘time‘,‘2018-6-16‘)print(obj.time)#delattr刪除delattr(obj,‘name‘)print(obj.name)#刪除後報錯AttributeError: ‘Foo‘ object has no attribute ‘name‘
Python ————反射機制