一.反射
通过字符串映射或者修改程序运行时的状态,属性,或者方法。
1.getattr(object,name,default=None)
2.hasattr(object,name)
3.setattr(x,y,v)
4.delattr(x,y)
1 class Dog(object):
2 def __init__(self,name):
3 self.name = name
4
5 def eat(self):
6 print("%s is eating ..." % self.name)
7
8 def bulk(self): #不在类里
9 print("%s is yelling.." %self.name)
10
11 d = Dog("zhangsan")
12 choice = input(">>:").strip()
13
14 if hasattr(d,choice): #判断一个对象里是否有对应的字符串的方法
15 func = getattr(d,choice) #根据字符串去获取对象里的对应的内存的方法
16 func()
17 else:
18 # setattr(d,choice,bulk) #is equivalent to 'x.y = v' d.talk = bulk的
19 # d.talk(d)
#这样写就写死了,func = getattr(d,choice)
# func(d)
20 21 setattr(d,choice,22) 22 a = getattr(d,choice) 23 print(a)
>>:age
22