时间:2021-05-22
英文文档:
getattr(object, name[, default])
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.
获取对象的属性值
说明:
1. 函数功能是从对象object中获取名称为name的属性,等效与调用object.name。
2. 函数第三个参数default为可选参数,如果object中含义name属性,则返回name属性的值,如果没有name属性,则返回default值,如果default未传入值,则报错。
#定义类Student>>> class Student: def __init__(self,name): self.name = name>>> getattr(s,'name') #存在属性name'Aim'>>> getattr(s,'age',6) #不存在属性age,但提供了默认值,返回默认值6>>> getattr(s,'age') #不存在属性age,未提供默认值,调用报错Traceback (most recent call last): File "<pyshell#17>", line 1, in <module> getattr(s,'age')AttributeError: 'Stduent' object has no attribute 'age'与__getattr__的区别:
__getattr__是类的内置方法,当找不到某个属性时会调用该方法;找到就不会调用.
getattr与类无关.
一个例子:作为data的代理类,可以以这种方式来使用data的属性.
class DataProxy(...): def __getattr__(self, item): return getattr(self.data, item)以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。
getattr()函数是Python自省的核心函数,具体使用大体如下:获取对象引用getattrGetattr用于返回一个对象属性,或者方法classA:def
getattr`getattr`函数属于内建函数,可以通过函数名称获取复制代码代码如下:value=obj.attributevalue=getattr(obj
反射在Python中,能够通过一个对象,找出type、class、attribute或者method的能力,成为反射。函数与方法内建函数:getattr(obj
反射在Python中,能够通过一个对象,找出type、class、attribute或者method的能力,成为反射。函数与方法内建函数:getattr(obj
本文实例讲述了C#通过属性名字符串获取、设置对象属性值操作.分享给大家供大家参考,具体如下:#通过反射获取对象属性值并设置属性值0、定义一个类publiccla