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,但提供了默認值,返回默認值 6 >>> getattr(s,'age') #不存在屬性age,未提供默認值,調(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)置方法,當找不到某個屬性時會調(diào)用該方法;找到就不會調(diào)用.
getattr與類無關(guān).
一個例子:作為data的代理類,可以以這種方式來使用data的屬性.
class DataProxy(...): def __getattr__(self, item): return getattr(self.data, item)
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Python元組 tuple的概念與基本操作詳解【定義、創(chuàng)建、訪問、計數(shù)、推導式等】
這篇文章主要介紹了Python元組 tuple的概念與基本操作,結(jié)合實例形式詳細分析了Python元組的定義、創(chuàng)建、訪問、計數(shù)、推導式等常見操作技巧與操作注意事項,需要的朋友可以參考下2019-10-10利用標準庫fractions模塊讓Python支持分數(shù)類型的方法詳解
最近在工作中遇到了分數(shù)處理,查找相關(guān)的資料發(fā)現(xiàn)可以利用Fraction類來實現(xiàn),所以下面這篇文章主要給大家介紹了關(guān)于利用標準庫fractions模塊讓Python支持分數(shù)類型的相關(guān)資料,文中通過示例代碼介紹的非常詳細,需要的朋友可以參考下。2017-08-08深入理解python中if?__name__?==?‘__main__‘
很多python的文件中會有語句if?__name=='__main__':,一直不太明白,最近查閱了一下資料,現(xiàn)在明白,本文就來深入理解一下,感興趣的可以了解一下2023-08-08Python在Excel中添加數(shù)據(jù)條的代碼詳解
在Excel中添加數(shù)據(jù)條是一種數(shù)據(jù)可視化技巧,它通過條形圖的形式在單元格內(nèi)直觀展示數(shù)值的大小,尤其適合比較同一列或行中各個單元格的數(shù)值,本文將介紹如何使用Python在Excel中的指定單元格區(qū)域添加數(shù)據(jù)條,需要的朋友可以參考下2024-10-10Python中使用kitti數(shù)據(jù)集實現(xiàn)自動駕駛(繪制出所有物體的行駛軌跡)
這篇文章主要介紹了Python中使用kitti數(shù)據(jù)集實現(xiàn)自動駕駛——繪制出所有物體的行駛軌跡,本次內(nèi)容主要是畫出kitti車的行駛的軌跡,需要的朋友可以參考下2022-06-06python opencv實現(xiàn)任意角度的透視變換實例代碼
這篇文章主要介紹了python opencv實現(xiàn)任意角度的透視變換實例代碼,具有一定借鑒價值,需要的朋友可以參考下2018-01-01Python爬取股票信息,并可視化數(shù)據(jù)的示例
這篇文章主要介紹了Python爬取股票信息,并可視化數(shù)據(jù)的示例,幫助大家更好的理解和使用python爬蟲,感興趣的朋友可以了解下2020-09-09