Python 反射,,反射 hasat


反射
hasattr(obj,name_str),判断一个对象里是否有对应的字符串的方法
getattr(obj,name_str),得到对象里对应字符串的方法,并执行

技术分享图片
 1 class Dog(object): 2     def __init__(self, name): 3         self.name = name 4  5     def eat(self, food): 6         print(‘%s is eating ... %s‘ % (self.name, food)) 7          8 def bluk(self): 9     print(‘%s is yell....‘ % self.name)10 11 12 d = Dog(‘dog1‘)13 14 choice = input(‘>>:‘)15 if hasattr(d, choice):16 17     # 删除属性18     delattr(d, choice)19     print(d.name)20 21     # 当输入name时,将name复制为dog22     # attr = getattr(d, choice)23     # setattr(d, choice, ‘dog2‘)24     # print(d.name)25 26     # 当输入eat时的代码27     # getattr(d, choice)(‘meat‘)28 29 else:30 31     # 无方法,给属性直接赋值32     setattr(d, choice, 22)33     print(getattr(d, choice))34 35     # setattr(d,choice,None)36     # print(getattr(d,choice))37 38     # setattr(d, choice, bluk)39     # d.talk(d)
View Code

Python 反射

评论关闭