Python 反射

 

反射
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复制为dog
22     # 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

 

posted @ 2018-05-08 23:03  Lin_pin  阅读(98)  评论(0编辑  收藏  举报