Python getattr()函数

版本

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

先看一下官网是如何定义getattr()函数:
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()函数大致的功能是:
获取对象的属性值。

1.获取变量的值

定义一个类,在其中添加变量

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

获取变量value的值

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

2.获取函数的值

在刚才定义好的类中添加一个函数

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

获取函数的值:

>>> getattr(clsTest, 'func')

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__')

你可能感兴趣的:(Python getattr()函数)