Manual
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.
直译
返回object中名为name的属性值。name必须是字符串,如果字符串是对象某个属性名,结果为该属性值,例如getattr(x, ‘foobar’)等价于x.foobar。如果给定的name不存在,会根据提供的默认值进行返回,否则会引发AttributeError。
实例
>>> class 优快云:
def foobar(self):
print('Hello 优快云er!')
>>> getattr(优快云, 'foobar')
<function 优快云.foobar at 0x03944F18>
>>> 优快云.foobar
<function 优快云.foobar at 0x03944F18>
本文详细介绍了Python内置函数getattr的功能及用法,包括如何通过字符串名称获取对象属性值,以及在属性不存在时如何处理。提供了具体示例并对比了getattr与其他相关函数的区别。
355

被折叠的 条评论
为什么被折叠?



