反射也叫路由系统,就是通过字符串的形式导入模块;通过字符串的形式去模块中寻找指定的函数,并执行,利用字符串的形式去对象(模块)中操作(查找、获取、删除、添加)成员,一种基于字符串的时间驱动。
获取:(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 >>>name15 Adair16 17 >>>age18 1819 20 >>>Show21>
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()12 UserInput=input(">>>")13 Get = getattr(obj,UserInput)14 Get()15 16 >>>Show17 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 >>>name14 True15 16 >>>Show17 True18 19 >>>Adair20 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>>>100000100000>>>name>>>xiaoheixiaohei
删除:(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 >>>name15 False
注:getattr,hasattr,setattr,delattr对模块的修改都在内存中进行,并不会影响文件中真实内容。