Python 反射
一、在本地文件中
1.getattr()函数
1 class Foo(): 2 def __init__(self,name,age): 3 self.name=name 4 self.age=age 5 def show(self): 6 print('%s-%s'%(self.name,self.age)) 7 f=Foo('alex',19) 8 input_str=input('Pls input the attribute:') 9 v=getattr(f,input_str) 10 print(v) 11 12 #Pls input the attribute:name 13 #alex
getattr(object,attribute)函数中object为对象,attribute为对象的属性(可以为变量/方法),返回值为该对象的属性的值,如果存在则返回不存在则报错
1 class Foo(): 2 def __init__(self,name,age): 3 self.name=name 4 self.age=age 5 def show(self): 6 print('%s-%s'%(self.name,self.age)) 7 f=Foo('alex',19) 8 input_str=input('Pls input the attribute:') 9 v=getattr(f,input_str) 10 print(v) 11 v() 12 13 #Pls input the attribute:show 14 #<bound method Foo.show of <__main__.Foo object at 0x000001D3346BDBE0>> 15 #alex-19
2.hasattr()函数
1 class Foo(): 2 def __init__(self,name,age): 3 self.name=name 4 self.age=age 5 def show(self): 6 print('%s-%s'%(self.name,self.age)) 7 f=Foo('alex',19) 8 v=hasattr(f,'show') 9 print(v) 10 11 #True
hasattr(object,attribute)函数object为对象,attribute为对象的属性(可以为变量/方法),返回值为该对象是否含有该属性,如果存在则返回True不存在则False
3.setattr()函数
1 class Foo(): 2 def __init__(self,name,age): 3 self.name=name 4 self.age=age 5 def show(self): 6 print('%s-%s'%(self.name,self.age)) 7 f=Foo('alex',19) 8 setattr(f,'gender','female') 9 print(f.gender) 10 11 #female
setattr(object,attribute,value)函数object为对象,attribute为对象的属性(可以为变量/方法),value为属性的值,该函数用来为对象设置属性并赋值
4.delattr()函数
1 class Foo(): 2 def __init__(self,name,age): 3 self.name=name 4 self.age=age 5 def show(self): 6 print('%s-%s'%(self.name,self.age)) 7 f=Foo('alex',19) 8 delattr(f,'name') 9 print(f.name) 10 #AttributeError: 'Foo' object has no attribute 'name'
delattr(object,attribute)函数object为对象,attribute为对象的属性(可以为变量/方法),该函数用来删除对象的属性
通过字符串去操作对象中的成员
二、在被引用作为模块时
1.模块内的全局变量
1 import processdemo 2 3 ret=getattr(processdemo,'Name') 4 print(ret) 5 #ALEX
2.模块内的普通方法
1 import processdemo 2 ret=getattr(processdemo,'Hi') 3 print(ret) 4 ret=ret() 5 print(ret) 6 7 #<function Hi at 0x000001BA19C0DF28> 8 #hello KuGou
3.模块内的类,以及类内部的成员
1 import processdemo 2 ret=getattr(processdemo,'Foo') 3 print(ret) 4 ret=ret() 5 print(ret) 6 ret=ret.name 7 print(ret) 8 9 #<class 'processdemo.Foo'> 10 #<processdemo.Foo object at 0x000001E532F9E320> 11 #hehe
三、获取选择
用于网页跳转
1 import processdemo 2 choice=input('pls input your choice:') 3 if hasattr(processdemo,choice): 4 func=getattr(processdemo,choice) 5 ret=func() 6 print(ret) 7 else: 8 print('404') 9 10 #pls input your choice:Hello 11 #hello SB
浙公网安备 33010602011771号