Python getattr()函數(shù)

版本

E:\Projects\testTool>python --version
Python 3.6.2

先看一下官網(wǎng)是如何定義getattr()函數(shù):
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.
從上面可以了解到getattr()函數(shù)大致的功能是:
獲取對象的屬性值。

1.獲取變量的值

定義一個類,在其中添加變量

>>> class clsTest():
...     value = 5

獲取變量value的值

>>> getattr(clsTest, 'value')
5

2.獲取函數(shù)的值

在剛才定義好的類中添加一個函數(shù)

>>> class clsTest():
...      value = 5
...      def func(self):
...         return 1 + 2

獲取函數(shù)的值:

>>> getattr(clsTest, 'func')
<function clsTest.func at 0x00000235D2EDCA60>

3.獲取類自帶屬性

使用dir()查看clsTest類中有哪些屬性

>>> dir(clsTest)
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'func', 'value']

試著查看其中class屬性的值:

>>> getattr(clsTest, '__class__')
<class 'type'>
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容