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')
>>> 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 "<pyshell#20>", line 1, in <module> 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
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。
相关文章
Python批量处理PDF图片的操作指南(插入、压缩、提取、替换、分页、旋转、删除)
图片是 PDF 文档的核心元素之一,它们不仅能够增强文档的视觉吸引力,还能有效传达信息,帮助读者更好地理解内容和主题,在实际操作中,我们常需要对PDF中的图片进行多种处理,这篇文章将详细介绍如何使用Python在PDF中实现图片插入、提取、替换、压缩等操作2025-04-04


最新评论