標籤:對象 pytho 就會 init 返回 str def try int
反射,通過字串映射到對象屬性
?
class People: country='China' def __init__(self,name,age): self.name=name self.age=age def talk(self): print('%s is talking' %self.name)p = People("gd", 22)print(p.name) # p.__dic__['name']print(p.talk) # <bound method People.talk of <__main__.People object at 0x00000000027B7470>>print(hasattr(p, 'name')) # True 判斷 對象p 裡有沒有 name 屬性, hasattr(),第一個參數傳對象,第二個參數傳 屬性名稱print(hasattr(p, 'talk1')) # Trueprint(getattr(p, 'name')) # gd 拿到 對象 p 裡的屬性# print(getattr(p, 'name2')) # AttributeError: 'People' object has no attribute 'name2'# getattr(), 沒有相應屬性的時候,會報錯,我們可以傳入第三個參數print(getattr(p, 'name2', None)) # None 這樣,找不到屬性的時候就會返回 None 了setattr(p, 'sex', '機器大師')print(p.sex) # 機器大師print(p.__dict__) # {'name': 'gd', 'age': 22, 'sex': '機器大師'}delattr(p, 'sex') # 刪除屬性print(p.__dict__) # {'name': 'gd', 'age': 22}# hasattr() getattr() setatter() delattr() 不僅適用於對象,也可以用於類print(hasattr(People, 'country')) # Trueprint(getattr(People, 'country')) # China
?
?
反射的應用
class Service: def run(self): while True: cmd = input(">>:").strip() if hasattr(self, cmd): func = getattr(self, cmd) func() def get(self): print('get......') def put(self): print('put.....')obj = Service()obj.run()# >>:get# get......# >>:put# put.....
Python—物件導向05 反射