Python getattr() 函数

getattr() 函数用于返回一个对象属性值。

getattr(object, name[, default])
  • object -- 对象。
  • name -- 字符串,对象属性。
  • default -- 默认返回值,如果不提供该参数,在没有对应属性时,将触发 AttributeErr

返回值

返回对象属性值。

 

简单示例理解:

class AA():
    def test(self,a):
        print(a)

aa = AA()
cc = getattr(aa,'test',False)
if not cc:
    print('ccc')
cc(a=11)
aa.test(a=22)

输出结果:

11
22

 

示例在不存在的情况下

class AA():
    def test(self,a):
        print(a)
    def test1(self,b):
        print(b)
aa = AA()
cc = getattr(aa,'tsest',False)
if not cc:
    print('ccc')
cc(a=11)
aa.test(a=22)

输入结果:

Traceback (most recent call last):
  File "C:/Users/Administrator/Desktop/test/test.py", line 10, in <module>
    cc(a=11)
TypeError: 'bool' object is not callable
ccc

 

posted @ 2022-01-28 11:32  乔小生1221  阅读(274)  评论(0编辑  收藏  举报