python------面向對象進階反射詳解(重點)
阿新 • • 發佈:2018-10-05
code one -- ... set bject pan strip() asa
一.反射
通過字符串映射或者修改程序運行時的狀態,屬性,或者方法。
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
python------面向對象進階反射詳解(重點)