python面向對象中的反射:經過字符串的形式操做對象相關的屬性。python中的一切事物都是對象(均可以使用反射)python
getattr # 根據字符串的形式,去對象中找成員。
hasattr # 根據字符串的形式,去判斷對象中是否有成員。
setattr # 根據字符串的形式,去判斷對象動態的設置一個成員(內存)
delattr # 根據字符串的形式,去判斷對象動態的設置一個成員(內存)
一、對象應用反射
class Foo: def __init__(self): self.name = 'egon' self.age = 51 def func(self): print('hello') egg = Foo() print(hasattr(egg,'name')) #先判斷name在egg裏面存在不存在,結果是True print(getattr(egg,'name')) #若是爲True它纔去獲得,結果是egon print(hasattr(egg,'func')) #結果是True print(getattr(egg,'func')) #獲得的是地址<bound method Foo.func of <__main__.Foo object at 0x0000000001DDA2E8>> getattr(egg,'func')() #在這裏加括號才能獲得,由於func是方法,結果是hello 通常用法以下,先判斷是否hasattr,而後取getattr if hasattr(egg,'func'): getattr(egg,'func')() #結果是hello else: print('沒找到')
二、類應用反射dom
class Foo: f = 123 @classmethod def class_method_dome(cls): print('class_method_dome') @staticmethod def static_method_dome(): print('static_method_dome') print(hasattr(Foo,'class_method_dome')) #結果是True method = getattr(Foo,'class_method_dome') method() #結果是class_method_dome print(hasattr(Foo,'static_method_dome')) #結果是True method1 = getattr(Foo,'static_method_dome') method1() #結果是static_method_dome