Python的getattr(),setattr(),delattr(),hasattr()

getattr()函數是Python自省的核心函數,具體使用大致以下:html

獲取對象引用getattr
Getattr用於返回一個對象屬性,或者方法app

  1. class A:   函數

  2.     def __init__(self):   ui

  3.         self.name = 'zhangjing'  spa

  4.     #self.age='24'orm

  5.     def method(self):   xml

  6.         print"method print"  htm

  7.   

  8. Instance = A()   對象

  9. print getattr(Instance 'name'not find'#若是Instance 對象中有屬性name則打印self.name的值,不然打印'not find'get

  10. print getattr(Instance 'age''not find')   #若是Instance 對象中有屬性age則打印self.age的值,不然打印'not find'

  11. print getattr(a, 'method''default')   

  12. #若是有方法method,不然打印其地址,不然打印default   

  13. print getattr(a, 'method''default')()   

  14. #若是有方法method,運行函數並打印None不然打印default  

注:使用getattr能夠輕鬆實現工廠模式。 
例:一個模塊支持html、text、xml等格式的打印,根據傳入的formate參數的不一樣,調用不一樣的函數實現幾種格式的輸出

  1. import statsout   

  2. def output(data, format="text"):                                

  3.      output_function = getattr(statsout, "output_%s" % format)   

  4.     return output_function(data)

>>> li=["zhangjing","zhangwei"]

>>> getattr(li,"pop")
<built-in method pop of list object at 0x011DF6C0>
>>> li.pop
<built-in method pop of list object at 0x011DF6C0>

>>> li.pop()
'zhangwei'

>>> getattr(li,"pop")()
'zhangjing'

>>>getattr(li, "append")("Moe") 

相關文章
相關標籤/搜索