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


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

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

Python代碼
  1. class A:   
  2.     def __init__(self):   
  3.         self.name = 'zhangjing'  
  4.     #self.age='24'
  5.     def method(self):   
  6.         print"method print"  
  7.   
  8. Instance = A()   
  9. print getattr(Instance , 'name, 'not find') #如果Instance 對象中有屬性name則打印self.name的值,否則打印'not find'
  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參數的不同,調用不同的函數實現幾種格式的輸出

 

Python代碼
    1. import statsout   
    2. def output(data, format="text"):                                
    3.      output_function = getattr(statsout, "output_%s" % format)   
    4.     return output_function(data)  

 

setattr( object, name, value)

This is the counterpart of getattr(). The arguments
are an object, a string and an arbitrary value. The string may name an existing
attribute or a new attribute. The function assigns the value to the attribute,
provided the object allows it. For example, setattr(x,
'foobar', 123)
is equivalent to
x.foobar = 123.

 這是相對應的getattr()。參數是一個對象,一個字符串和一個任意值。字符串可能會列出一個現有的屬性或一個新的屬性。這個函數將值賦給屬性的。該對象允許它提供。例如,setattr(x,“foobar”,123)相當於x.foobar = 123。

delattr(       object, name)

This is a relative of setattr(). The arguments are
an object and a string. The string must be the name of one of the object’s
attributes. The function deletes the named attribute, provided the object allows
it. For example, delattr(x, 'foobar') is
equivalent to del x.foobar.

與setattr()相關的一組函數。參數是由一個對象(記住python中一切皆是對象)和一個字符串組成的。string參數必須是對象屬性名之一。該函數刪除該obj的一個由string指定的屬性。delattr(x, 'foobar')=del x.foobar

 

 

  • hasattr用於確定一個對象是否具有某個屬性。

    語法:
     hasattr(object, name) -> bool
    判斷object中是否有name屬性,返回一個布爾值。
    

>>> 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") 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM