Python setattr()

Python setattr() function allows us to set an object attribute value.

Python setattr()函数允许我们设置对象属性值。

Python setattr() (Python setattr())

Python setattr() function syntax is:

Python setattr()函数语法为:

setattr(object, name, value)

This function is counterpart of python getattr() function.

该函数与python getattr()函数相对应。

The input arguments are object whose attribute will be set, name is the attribute name and value is the attribute value.

输入参数是将设置属性的objectname是属性名称, value是属性值。

Let’s look at a simple example of setattr() function.

我们来看一个简单的setattr()函数示例。

class Data:passd = Data()d.id = 10print(d.id)setattr(d, 'id', 20)
print(d.id)

Output:

输出:

10
20

So setattr() does the exact same thing as using dot operator with the object.

因此,setattr()的作用与对对象使用点运算符的作用完全相同。

So where is the benefit of using setattr() function?

那么使用setattr()函数的好处在哪里呢?

The setattr() function is useful in dynamic programming where the attribute name is not static. In that case, we can’t use the dot operator. For example, taking user input to set an object attribute and its value.

setattr()函数在属性名称不是静态的动态编程中很有用。 在这种情况下,我们不能使用点运算符。 例如,以用户输入来设置对象属性及其值。

用户输入的Python setattr()示例 (Python setattr() example with user input)

d = Data()
attr_name = input('Enter the attribute name:n')
attr_value = input('Enter the attribute value:n')setattr(d, attr_name, attr_value)print('Data attribute =', attr_name, 'and its value =', getattr(d, attr_name))

Output:

输出:

Enter the attribute name:
name
Enter the attribute value:
Pankaj
Data attribute = name and its value = Pankaj

Python setattr()异常 (Python setattr() exception)

We can create a read-only attribute in the object using property function or property decorator.

我们可以使用property function或property decorator在对象中创建一个只读属性。

In that case, if we try to set the attribute value using setattr() function, we will get AttributeError: can't set attribute exception.

在这种情况下,如果尝试使用setattr()函数设置属性值,则会得到AttributeError: can't set attribute异常。

class Person:def __init__(self):self._name = Nonedef get_name(self):print('get_name called')return self._name# for read-only attributename = property(get_name, None)p = Person()setattr(p, 'name', 'Pankaj')

Output:

输出:

Traceback (most recent call last):File "/Users/pankaj/Documents/github/journaldev/Python-3/basic_examples/python_setattr_example.py", line 39, in <module>setattr(p, 'name', 'Pankaj')
AttributeError: can't set attribute

GitHub Repository.GitHub存储库中检出完整的python脚本和更多Python示例。

Reference: Official Documentation

参考: 官方文档

翻译自: https://www.journaldev.com/23129/python-setattr

Published by

风君子

独自遨游何稽首 揭天掀地慰生平