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