反射:通过字符串对一个类中的方法,变量进行判断获取添加和删除,也就是通过字符串反射到类中的方法和变量
一共有四个方法:
1.getattr(obj,str):获取obj中的str的内存地址
2.hasattr(obj,str):判断obj中是否有对应的str方法或变量
3.setattr(obj,str,方法或变量):当输入str的时候,在obj中添加后边的方法或变量,讲一个外面的方法添加到类中
4.delattr(obj,str):删除obj中对应的str方法或变量
示例代码:
#外面的方法
def play(self):
print("%s is playing...." %self.name)
#人这个类
class person(object):
def __init__(self,name):
self.name = name
def eat(self):
print("%s is eating..."%self.name)
#创建人这个对象
d = person("wuxie")
#输入内容赋给choice
choice = input(">>:").strip()
#判断是否有choice
if hasattr(d,choice):
getattr(d,choice)()
else:
setattr(d,choice,play) #d.talk = bulk
func = getattr(d, choice)
func(d)