版本
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'>