Python通過getattr函數(shù)獲取對象的屬性值
英文文檔:
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, default is returned if provided, otherwise AttributeError is raised.
獲取對象的屬性值
說明:
1. 函數(shù)功能是從對象object中獲取名稱為name的屬性,等效與調(diào)用object.name。
#定義類Student>>> class Student: def __init__(self,name): self.name = name >>> s = Stduent(’Aim’)>>> getattr(s,’name’) #等效于調(diào)用s.name’Aim’>>> s.name’Aim’
2. 函數(shù)第三個參數(shù)default為可選參數(shù),如果object中含義name屬性,則返回name屬性的值,如果沒有name屬性,則返回default值,如果default未傳入值,則報錯。
#定義類Student>>> class Student: def __init__(self,name): self.name = name>>> getattr(s,’name’) #存在屬性name’Aim’>>> getattr(s,’age’,6) #不存在屬性age,但提供了默認(rèn)值,返回默認(rèn)值6>>> getattr(s,’age’) #不存在屬性age,未提供默認(rèn)值,調(diào)用報錯Traceback (most recent call last): File '<pyshell#17>', line 1, in <module> getattr(s,’age’)AttributeError: ’Stduent’ object has no attribute ’age’
與__getattr__的區(qū)別:
__getattr__是類的內(nèi)置方法,當(dāng)找不到某個屬性時會調(diào)用該方法;找到就不會調(diào)用.
getattr與類無關(guān).
一個例子:作為data的代理類,可以以這種方式來使用data的屬性.
class DataProxy(...): def __getattr__(self, item): return getattr(self.data, item)
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. python 讀txt文件,按‘,’分割每行數(shù)據(jù)操作2. Python 忽略文件名編碼的方法3. JavaEE SpringMyBatis是什么? 它和Hibernate的區(qū)別及如何配置MyBatis4. 解決vue頁面刷新,數(shù)據(jù)丟失的問題5. android studio實現(xiàn)簡單的計算器(無bug)6. Java Media Framework 基礎(chǔ)教程7. 在Mac中配置Python虛擬環(huán)境過程解析8. python如何實現(xiàn)word批量轉(zhuǎn)HTML9. 利用單元測試對PHP代碼進行檢查10. python excel和yaml文件的讀取封裝
