在python中,反射包含如下幾個函數python
def hasattr(*args, **kwargs): # real signature unknown """ Return whether the object has an attribute with the given name. This is done by calling getattr(obj, name) and catching AttributeError. """ pass
def hasattr(*args, **kwargs): # real signature unknown """ Return whether the object has an attribute with the given name. This is done by calling getattr(obj, name) and catching AttributeError. """ pass
def setattr(x, y, v): # real signature unknown; restored from __doc__ """ Sets the named attribute on the given object to the specified value. setattr(x, 'y', v) is equivalent to ``x.y = v'' """ pass
def delattr(x, y): # real signature unknown; restored from __doc__ """ Deletes the named attribute from the given object. delattr(x, 'y') is equivalent to ``del x.y'' """ pass
In [1]: class Person(object): ...: def __init__(self, name, age): ...: self.name = name ...: self.age = age In [2]: p = Person('hkey', 20) # 實例化一個對象 In [3]: hasattr(p, 'name') # 經過 hasattr 判斷 p 是否包含 name 屬性,這裏name參數必須是字符串類型 Out[3]: True In [4]: hasattr(p, 'sex') # 若是 p 中沒有 sex 屬性,則返回 False Out[4]: False
In [5]: getattr(p, 'name') # p.name = getattr(p, 'name') Out[5]: 'hkey' In [6]: getattr(p, 'age') # p.age = getattr(p, 'age') Out[6]: 20 In [7]: getattr(p, 'sex') # p.sex = getattr(p, 'sex') p 對象中不包含 sex 屬性則報錯. --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-7-36d4b75cf6b8> in <module> ----> 1 getattr(p, 'sex') AttributeError: 'Person' object has no attribute 'sex'
getattr 進階用法:shell
當使用 getattr 獲取不存在屬性的時候,咱們不但願直接拋出異常。bash
getattr(對象, 'str1', '對象屬性不存在時的默認信息')
In [16]: getattr(p, 'sex', '不知道') # p 對象中是沒有 sex 屬性,直接返回默認值 Out[16]: '不知道' In [17]: getattr(p, 'sex', 'None') # 通常來講直接設置爲 None Out[17]: 'None'
In [8]: setattr(p, 'sex', 'male') # 經過 setattr 爲 p 對象設置爲 sex 屬性,屬性值爲 male In [9]: p.sex # 驗證 setattr 是否設置成功 Out[9]: 'male'
setattr 進階用法:ide
setattr 不只能夠爲對象添加屬性,還能夠爲對象綁定方法函數
In [23]: setattr(p, 'say_hello', lambda self: 'hello, ' + self.name) # setattr(對象名, '方法名', '匿名函數') self 表明對象自己 In [24]: p.say_hello(p) # 調用方式必須將對象傳入 對象.方法名(對象) Out[24]: 'hello, hkey'
In [10]: delattr(p, 'sex') # 經過 delattr 刪除 p 對象的 sex 屬性 In [11]: p.sex # 驗證 sex 屬性是否刪除成功 --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-13-0e282ee1b157> in <module> ----> 1 p.sex AttributeError: 'Person' object has no attribute 'sex'
反射在實際代碼中使用的很是廣泛,尤爲是在和用戶交互的時候。ui
實例:自行編寫一個shell,當要執行一個命令的時候使用反射來執行spa
import os class Manage_cmd(object): def run(self): while True: cmd = input('>>>').strip() if not cmd: continue if hasattr(self, cmd): # 經過 hasattr 來判斷對象self是否含有cmd屬性 getattr(self, cmd)() else: print('-bash: %s: command not found' % cmd) def ls(self): print(os.listdir('.')) def exit(self): exit(1) cmd = Manage_cmd() cmd.run()
執行結果:rest