反射
1 # 反射: 2 # hasattr() 判断一个对象里是否有对应的 name_str 字符串的方法 3 # getattr() 根据字符串获得对象里的对应的方法的内存地址 后面+()可调用 4 # setattr(obj, 'name', value) 通过字符串设置一个值 5 # delattr(obj, "str") 6 def eat(self): 7 print("eat") 8 9 class Dog(object): 10 def __init__(self, name, age): 11 self.name = name 12 self.age = age 13 14 def talk(self, who): 15 print("%s is talking wangwangwnag with %s!"% (self.name, who)) 16 17 d = Dog("L", 11) 18 action = input("action:>>").strip() 19 20 if hasattr(d, action): 21 func = getattr(d, action) 22 func("Jy") 23 print(d.name) 24 delattr(d, 'name') 25 else: 26 setattr(d, action, eat) 27 func = getattr(d, action) 28 func(d) 29 print(d.name)