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')
<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'>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容