030反射
###反射
## getattr,hasattr,setattr,delattr,和类里面的字段有关,具体看例子
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#1 class Person: def __init__(self,name,age): self.name = name self.age = age def show_lover(self): print('lover') o = Person('x',21) b = 'name' print(o.__dict__[b]) # 2 b = input('>>>') if hasattr(o,b): v = getattr(o,b) # 去什么东西里面获取什么内容 delattr(o,b) setattr(o,'age',21) print(v) func=getattr(o,'show_lover') # 拿到方法 func()
# 3 拿到类对象的字段
class Person: stat = '123' def __init__(self,name,age): self.name = name self.age = age r = getattr(Person,'stat') print(r)
# 4拿到其他模块的函数和字段等
# s.py NAME = '_nbloser' def func(): return'func' class Person: def __init__(self): self.name = '_nbloser'
# 执行.py import s r1 = getattr(s,'NAME') r2 = getattr(s,'func') Pers = getattr(s,'Person') p1 = Pers() print(r1,r2(),p1.name) # _nbloser func _nbloser
# 应用小例子
def f1(): return'首页' def f2(): return'新闻' def f3(): return'精华' import s inp = input('>>') if hasattr(s,inp): func = getattr(s,inp) print(func()) else: print(404)