温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Python的hasattr()、getattr()、setattr()函数怎么用

发布时间:2022-04-22 13:47:55 来源:亿速云 阅读:144 作者:iii 栏目:开发技术

本文小编为大家详细介绍“Python的hasattr()、getattr()、setattr()函数怎么用”,内容详细,步骤清晰,细节处理妥当,希望这篇“Python的hasattr()、getattr()、setattr()函数怎么用”文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起来学习新知识吧。

hasattr()

hasattr() 函数用来判断某个类实例对象是否包含指定名称的属性或方法。
该函数的语法格式如下:

hasattr(obj, name)

其中 obj 指的是某个类的实例对象,name 表示指定的属性名或方法名,返回BOOL值,有name特性返回True, 否则返回False。

例子:

class demo:
    def __init__ (self):
        self.name = "lily"
    def say(self):
        print("say hi")
d = demo()
print(hasattr(d, 'name'))
print(hasattr(d, 'say'))
print(hasattr(d, 'eat'))

运行结果如下:

True
True
False

getattr()

getattr() 函数获取某个类实例对象中指定属性的值。
该函数的语法格式如下:

getattr(object, name[, default])

其中,obj 表示指定的类实例对象,name 表示指定的属性名,而 default 是可选参数,用于设定该函数的默认返回值,即当函数查找失败时,如果不指定 default 参数,则程序将直接报 AttributeError 错误,反之该函数将返回 default 指定的值。

例子:

class demo:
    def __init__ (self):
        self.name = "lily"
    def say(self):
        return "say hi"
d = demo()
print(getattr(d, 'name'))
print(getattr(d, 'say'))
print(getattr(d, 'eat'))

运行结果如下:

lily
<bound method demo.say of <__main__.demo object at 0x7f31c630d0a0>>
Traceback (most recent call last):
  File "/test.py", line 11, in <module>
    print(getattr(d, 'eat'))
AttributeError: 'demo' object has no attribute 'eat'

可以看到,对于类中已有的属性,getattr() 会返回它们的值,而如果该名称为方法名,则返回该方法的状态信息;反之,如果该明白不为类对象所有,要么返回默认的参数,要么程序报 AttributeError 错误。
需要注意的是,如果是返回的对象的方法,返回的是方法的内存地址,如果需要运行这个方法,可以在后面添加一对括号。比如:

class demo:
    def __init__ (self):
        self.name = "lily"
    def say(self):
        return "say hi"
    def eat(self, something):
        return f"eat {something}"
d = demo()
print(getattr(d, 'name'))
print(getattr(d, 'say'))
print(getattr(d, 'eat')('apple'))
print(getattr(d, 'eat', 'no eat')('banana'))

运行结果如下:

lily <bound method demo.say of <__main__.demo object at 0x7fe99b1ca0a0>> eat apple eat banana

setattr()

setattr() 函数最基础的功能是修改类实例对象中的属性值。其次,它还可以实现为实例对象动态添加属性或者方法。
该函数的语法格式如下:

setattr(obj, name, value)

例子:

class demo:
    def __init__ (self):
        self.name = "lily"

d = demo()
print(getattr(d, 'name'))
print('----------')
setattr(d, 'name', 'tom')
print(getattr(d, 'name'))
print('----------')
print(hasattr(d, 'age'))
setattr(d, 'age', '18')
print(hasattr(d, 'age'))
print(getattr(d, 'age'))

运行结果如下:

lily
----------
tom
----------
False
True
18

读到这里,这篇“Python的hasattr()、getattr()、setattr()函数怎么用”文章已经介绍完毕,想要掌握这篇文章的知识点还需要大家自己动手实践使用过才能领会,如果想了解更多相关内容的文章,欢迎关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI