反射这个功能在很多编程语言中都有,在Python中自然也不例外。其实编程语言中的很多功能都能用简单的代码来验证。
在code代码之前,先简单的了解下反射的几个属性。
hasattr(obj,name_str) 判断一个对象里是否存在某个字符串方法
getattr() 如果存在就获取,然后执行...
setattr() 如果不存在想设置,然后在执行...
delattr() 如果存在自然可以删除
1 def bulk(self):
2 print 'wangwang ....'
3
4 class Dog(object):
5 def __init__(self,name):
6 self.name = name
7
8 def eat(self,food):
9 print '%s is eating...%s' % (self.name,food)
10
11 d = Dog('XIAOHEI')
12
13 choice = raw_input('>>:').strip()
14 #print hasattr(d,choice)
15 if hasattr(d,choice):
16 #delattr(d,choice)
17 func = getattr(d,choice)
18 #print func <bound method Dog.eat of <__main__.Dog object at 0x10bacd590>>
19 func('bread')
20 else:
21 #print 'obj has no attribute'
22 setattr(d,choice,bulk)
23 func = getattr(d,choice)
24 func(d)
输入eat
XIAOHEI is eating...bread
输入bulk
wangwang ....
是不是很easy!