• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

Python使用内置函数setattr设置对象的属性值

python 搞代码 4年前 (2022-01-07) 46次浏览 已收录 0个评论

这篇文章主要介绍了Python使用内置函数setattr设置对象的属性值,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

英文文档:

setattr(object, name, value)

This is the counterpart of getattr(). The arguments are an object, a string and an arbitrary value. The string may name an existing attribute or a new attribute. The function assigns the value to the attribute, provided the object allows it. For example, setattr(x, ‘foobar’, 123) is equivalent to x.foobar = 123

  设置对象的属性值

说明:

  1. setattr函数和getattr函数是对应的。一个设置对象的属性值,一个获取对象属性值。

  2. 函数有3个参数,功能是对参数object对象,设置名为name的属性的属性值为value值。

 >>> class Student: def __init__(self,name): self.name = name >>> a = Student('Kim') >><b style="color:transparent">来源gao@!dai!ma.com搞$$代^@码网</b>> a.name 'Kim' >>> setattr(a,'name','Bob') >>> a.name 'Bob'

  3. name属性可以是object对象的一个已经存在的属性,存在的话就会更新其属性值;如果name属性不存在,则对象将创建name名称的属性值,并存储value值。等效于调用object.name = value。

 >>> a.age # 不存在age属性 Traceback (most recent call last): File "", line 1, in  a.age AttributeError: 'Student' object has no attribute 'age' >>> setattr(a,'age',10) # 执行后 创建 age属性 >>> a.age # 存在age属性了 10 >>> a.age = 12 # 等效于调用object.name >>> a.age 12

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持gaodaima搞代码网

以上就是Python使用内置函数setattr设置对象的属性值的详细内容,更多请关注gaodaima搞代码网其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:Python使用内置函数setattr设置对象的属性值

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址