Tutorial Study Image

Python setattr()

内置函数 setattr() 用于为指定对象的指定属性赋值。


setattr(object, name, value) #where object indicates whose attribute value is needs to be change

setattr() 参数

接受三个参数。我们可以说 setattr() 等同于 object.attribute = value。

参数 描述 必需/可选
对象 要设置属性的对象 必需
名称 属性名 必需
value 赋予属性的值 必需

setattr() 返回值

setattr() 方法不返回任何内容,它只为对象的属性赋值。此函数在动态编程中很有用,在这种情况下我们不能使用“点”运算符赋值。

Python 中 setattr() 方法的示例

示例 1: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: John

示例 2:当在 setattr() 中找不到属性时


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: 23

示例 3:Python setattr() 异常情况


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