#Author:'wbing' #-*-coding:utf-8-*- ''' 反射,就是将字符串转为可以调用的方法,可以实现用户动态交互 hasattr(对象,字符串),判断对应的方法函数是否在类里面 getattr(对象, 字符串),返回内存地址,通过getattr(对象, 字符串)()调用 setattr(对象,字符串,func),将类外面的函数(属性)装到类里面,格式:对象.字符串=func delattr(对象,字符串),删除对象或者属性 ''' def bulk(self): print('%s is yelling'%self.name) class Dog(object): def __init__(self,name): self.name = name def eat(self): print('%s is eating'%self.name) d = Dog('狗') choice = input('>>:').strip() #用户输入什么就调用什么方法,字符串不可以直接d.choice调用,需要反射 if hasattr(d,choice): #hasattr(obj,str),判断对应的方法函数是否在类里面 # delattr(d,choice)#删除属性或者函数,调用就会报错 getattr(d, choice)#返回内存地址 # <bound method Dog.eat of <__main__.Dog object at 0x000002649D049860>> func = getattr(d, choice) func() else: setattr(d,choice,bulk) #x.'y'=z, d.choice=bulk,设置添加一个函数 # setattr(d, choice,None) #x.'y'=z,也可以设置添加一个属性 #d.talk(d) #调用添加的函数,需要传入self参数,其中talk只要与choice一致即可 func = getattr(d,choice)#使用getattr调用获取添加的函数的内存地址 func(d)#调用添加的函数
python-反射
最新推荐文章于 2019-01-01 18:58:28 发布