python 反射機制
阿新 • • 發佈:2018-09-14
bject key sat 是否 NPU bsp list.sh 查找 spa
反射也叫路由系統,就是通過字符串的形式導入模塊;通過字符串的形式去模塊中尋找指定的函數,並執行,利用字符串的形式去對象(模塊)中操作(查找、獲取、刪除、添加)成員,一種基於字符串的時間驅動。
獲取:(getattr:獲取或執行對象中的對象)
1 class NameList(): 2 def __init__(self,name,age): 3 self.name = name 4 self.age = age 5 6 def Show(self): 7 print("My name is %s and I‘m %d years old" %(self.name,self.age)) 8 9 obj = NameList("Adair",18) 10 # obj.Show() 11 UserInput=input(">>>") 12 print(getattr(obj,UserInput)) 13 14 >>>name 15 Adair 16 17 >>>age 18 18 19 20 >>>Show 21 <bound method NameList.Show of <__main__.NameList object at 0x000001F6CADEB358>>
1 getattr 調用函數: 2 class NameList(): 3 def __init__(self,name,age): 4 self.name = name 5 self.age = age 6 7 def Show(self): 8 print("My name is %s and I‘m %d years old" %(self.name,self.age)) 9 10 obj = NameList("Adair",18) 11 # obj.Show() 12UserInput=input(">>>") 13 Get = getattr(obj,UserInput) 14 Get() 15 16 >>>Show 17 My name is Adair and I‘m 18 years old
查找:(hasattr:判斷方式是否存在與對象中)
1 class NameList(): 2 def __init__(self,name,age): 3 self.name = name 4 self.age = age 5 6 def Show(self): 7 print("My name is %s and I‘m %d years old" %(self.name,self.age)) 8 9 obj = NameList("Adair",18) 10 UserInput=input(">>>") 11 print(hasattr(obj,UserInput)) 12 13 >>>name 14 True 15 16 >>>Show 17 True 18 19 >>>Adair 20 False
添加/修改(setattr)
class NameList(): def __init__(self,name,age): self.name = name self.age = age def Show(self): print("My name is %s and I‘m %d years old" %(self.name,self.age)) obj = NameList("Adair",18) InputKey=input(">>>") InputValue=input(">>>") New = setattr(obj,InputKey,InputValue) print(getattr(obj,InputKey)) >>>salary >>>100000 100000 >>>name >>>xiaohei xiaohei
刪除:(delattr)
1 class NameList(): 2 def __init__(self,name,age): 3 self.name = name 4 self.age = age 5 6 def Show(self): 7 print("My name is %s and I‘m %d years old" %(self.name,self.age)) 8 9 obj = NameList("Adair",18) 10 UserInput=input(">>>") 11 delattr(obj,UserInput) 12 print(hasattr(obj,UserInput)) 13 14 >>>name 15 False
註:getattr,hasattr,setattr,delattr對模塊的修改都在內存中進行,並不會影響文件中真實內容。
python 反射機制