Python中g(shù)etattr用法

1、官方文檔

getattr(object, name[, default])
Return the value of the named attribute of object. name must be a string. 
If the string is the name of one of the object’s attributes, 
the result is the value of that attribute. 
For example, getattr(x, 'foobar') is equivalent to x.foobar. 
If the named attribute does not exist, defaultis returned if provided, 
otherwise AttributeError is raised.

官方文檔中說這個函數(shù)作用是返回對象的一個屬性,第一個參數(shù)是對象實例obj,name是個字符串,是對象的成員函數(shù)名字或者成員變量,default當(dāng)對象沒有這個屬相的時候就返回默認值,如果沒有提供默認值就返回異常。

>>> class Test(object):
...     def func(self):
...             print 'I am a test'
...
>>> test = Test()  # 實例化一個對象
>>> func = getattr(test, 'func') # 使用getattr函數(shù)獲取func的值
>>> func()
I am a test
>>> func = getattr(test, 'f')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'Test' object has no attribute 'f'

>>> func = getattr(test, 'f')  # 使用對象沒有的屬性,則會出現(xiàn)異常
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'Test' object has no attribute 'f'
>>>

2、提供默認值的寫法

如果對象沒有該屬性可以提供一個默認值。

>>> func = getattr(test, 'f', None)
>>> print func
None
>>>

3、使用getattr函數(shù)實現(xiàn)工廠模式

實現(xiàn)一個模塊支持不用格式的打印,如html、text(默認)等格式,傳入formate不同調(diào)用不同方法

def print_format(data, format='text'):
    # 需要對fomat參數(shù)進行驗證
    output_function = getattr(obj, 'output_%s' % format, None)
    if not output_function:  # 沒有提供的方法
        return 
    return output_function(data)  # 使用對應(yīng)的方法進行打印

參考文章http://www.cnblogs.com/pylemon/archive/2011/06/09/2076862.html

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 134,948評論 18 139
  • *面試心聲:其實這些題本人都沒怎么背,但是在上海 兩周半 面了大約10家 收到差不多3個offer,總結(jié)起來就是把...
    Dove_iOS閱讀 27,211評論 30 472
  • 前言 人生苦多,快來 Kotlin ,快速學(xué)習(xí)Kotlin! 什么是Kotlin? Kotlin 是種靜態(tài)類型編程...
    任半生囂狂閱讀 26,276評論 9 118
  • 1.常見用法 電腦基本操作ctrl+c 復(fù)制ctrl+v 粘貼ct...
    莫失丿莫忘閱讀 251評論 0 1