十年网站开发经验 + 多家企业客户 + 靠谱的建站团队
量身定制 + 运营维护+专业推广+无忧售后,网站问题一站解决
内置函数setattr()用于将给定值赋给指定对象的指定属性。

创新互联主要从事成都做网站、成都网站建设、成都外贸网站建设、网页设计、企业做网站、公司建网站等业务。立足成都服务明水,10余年网站建设经验,价格优惠、服务专业,欢迎来电咨询建站服务:028-86922220
**setattr(object, name, value)** #where object indicates whose attribute value is needs to be changesetattr()参数:取三个参数。我们可以说setattr()相当于 object.attribute = value。
| 参数 | 描述 | 必需/可选 |
|---|---|---|
| 目标 | 必须设置其属性的对象 | 需要 |
| 名字 | 属性名 | 需要 |
| 价值 | 该值被赋予该属性 | 需要 |
setattr()返回值setattr()方法不返回任何东西,它只分配对象属性值。这个函数在动态编程中很有用,在这种情况下,我们不能使用“点”运算符来分配属性值。
setattr()方法的示例setattr()在 Python 中是如何工作的? class PersonName:
name = 'Dany'
p = PersonName()
print('Before modification:', p.name)
# setting name to 'John'
setattr(p, 'name', 'John')
print('After modification:', p.name)
输出:
Before modification: Dany
After modification: Johnsetattr()中找不到属性时 class PersonName:
name = 'Dany'
p = PersonName()
# setting attribute name to John
setattr(p, 'name', 'John')
print('Name is:', p.name)
# setting an attribute not present in Person
setattr(p, 'age', 23)
print('Age is:', p.age)
输出:
Name is: John
Age is: 23setattr()异常情况 class PersonName:
def __init__(self):
self._name = None
def get_name(self):
print('get_name called')
return self._name
# for read-only attribute
name = property(get_name, None)
p = PersonName()
setattr(p, 'name', 'Sayooj')
输出:
Traceback (most recent call last):
File "/Users/sayooj/Documents/github/journaldev/Python-3/basic_examples/python_setattr_example.py", line 39, in setattr(p, 'name', 'Sayooj')
AttributeError: can't set attribute