python getattr函数

人气:222 ℃/2022-12-01 18:10:33

python getattr函数是怎样的呢?下面就让我们一起来了解一下吧:

getattr函数是属于python下的一个函数,getattr()函数可以用于返回一个对象属性值。

具体的语法格式为:

getattr(object,name[,default])

参数说明:

object 对象。

name 字符串,对象属性。

default 默认返回值,若是不提供该参数,在没有对应属性时,将触发AttributeError。

返回值:

返回对象属性值。

参考范例:

>>>classA(object):...bar=1...>>>a=A()>>>getattr(a,'bar')#获取属性bar值1>>>getattr(a,'bar2')#属性bar2不存在,触发异常Traceback(mostrecentcalllast):File"",line1,inAttributeError:'A'objecthasnoattribute'bar2'>>>getattr(a,'bar2',3)#属性bar2不存在,但设置了默认值3>>>

以上就是小编的分享了,希望能够帮助到大家。

python getattr用法

Python的hasattr() getattr() setattr() 函数使用方法详解

>>> class test():... name="xiaohua"... def run(self):... return "HelloWord"...>>> t=test()>>> hasattr(t, "name") #判断对象有name属性True>>> hasattr(t, "run") #判断对象有run方法True>>>

>>> class test():... name="xiaohua"... def run(self):... return "HelloWord"...>>> t=test()>>> hasattr(t, "age") #判断属性是否存在False>>> setattr(t, "age", "18") #为属相赋值,并没有返回值>>> hasattr(t, "age") #属性存在了True>>>

>>> class test():... name="xiaohua"... def run(self):... return "HelloWord"...>>> t=test()>>> hasattr(t, "age") #判断属性是否存在False>>> setattr(t, "age", "18") #为属相赋值,并没有返回值>>> hasattr(t, "age") #属性存在了True>>>

一种综合的用法是:判断一个对象的属性是否存在,若不存在就添加该属性。

>>> class test():... name="xiaohua"... def run(self):... return "HelloWord"...>>> t=test()>>> getattr(t, "age") #age属性不存在Traceback (most recent call last): File "<stdin>", line 1, in <module>AttributeError: test instance has no attribute 'age'>>> getattr(t, "age", setattr(t, "age", "18")) #age属性不存在时,设置该属性'18'>>> getattr(t, "age") #可检测设置成功'18'>>>

推荐

首页/电脑版/网名
© 2025 NiBaKu.Com All Rights Reserved.