Python的getattr(),setattr(),delattr(),hasattr()及類內建__getattr__應用

來源:互聯網
上載者:User

標籤:

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

先轉一篇博文,參考。最後再給出一個例子

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

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

  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參數的不同,調用不同的函數實現幾種格式的輸出

 

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

 

--------------------------------------------------------------------------------------------------------------------------------------------------------

例子如下: 
 1 class WrapMe(object): 2     """docstring for ClassName""" 3     def __init__(self, arg): 4          5         self.__data = arg 6     def get(self): 7         return self.__data 8     def __repr__(self): 9         return ‘self.__data‘10     def __str__(self):11         return str(self.__data)12     def __getattr__(self,attr):13         return getattr(self.__data,attr)14 wrappedComplex = WrapMe(3.5+4.2j)        15 print wrappedComplex16 print wrappedComplex.real17 print wrappedComplex.imag18 print wrappedComplex.conjugate()19 print wrappedComplex.get()

結果如下:

對象自有方法:

 

 

 

 

----------------------------------------------------------

類內建是對象的擷取,內建是擷取XX中的XXX方法結果

Python的getattr(),setattr(),delattr(),hasattr()及類內建__getattr__應用

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.