python 内建函数setattr() getattr()

本文介绍Python中用于操作对象属性的内置函数setattr()和getattr()。通过示例演示如何使用这两个函数来设置和获取对象属性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

python 内建函数setattr() getattr()

setattr(object,name,value):

作用:设置object的名称为name(type:string)的属性的属性值为value,属性name可以是已存在属性也可以是新属性。

getattr(object,name,default):

作用:返回object的名称为name的属性的属性值,如果属性name存在,则直接返回其属性值;如果属性name不存在,则触发AttribetError异常或当可选参数default定义时返回default值。

<!-- lang: python -->
>>> class attribute():
...     def __init__(self):
...             self.attribute_1='i am attribute 1'
...             self.attribute_2='i am attribute 2'
...
>>> result=attribute()
>>> dir(result)
['__doc__', '__init__', '__module__', 'attribute_1', 'attribute_2']
>>> getattr(result,'attribute_1') 'i am attribute 1' >>> getattr(result,'attribute_3') Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: attribute instance has no attribute 'attribute_3' >>> getattr(result,'attribute_3','i am attribute 3') 'i am attribute 3' >>> dir(result) ['__doc__', '__init__', '__module__', 'attribute_1', 'attribute_2'] >>> getattr(result,'attribute_2') 'i am attribute 2' >>> setattr(result,'attribute_2','i am changed') >>> getattr(result,'attribute_2') 'i am changed' >>> setattr(result,'attribute_4','i am new one') >>> dir(result) ['__doc__', '__init__', '__module__', 'attribute_1', 'attribute_2', 'attribute_4']

转载于:https://www.cnblogs.com/yymn/p/5583233.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值