本文共 2369 字,大约阅读时间需要 7 分钟。
Python setattr() function allows us to set an object attribute value.
Python setattr()函数允许我们设置对象属性值。
Python setattr() function syntax is:
Python setattr()函数语法为:
setattr(object, name, value)
This function is counterpart of function.
该函数与函数相对应。
The input arguments are object
whose attribute will be set, name
is the attribute name and value
is the attribute value.
输入参数是将设置属性的object
, name
是属性名称, 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:
输出:
1020
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()函数在属性名称不是静态的动态编程中很有用。 在这种情况下,我们不能使用点运算符。 例如,以用户输入来设置对象属性及其值。
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:nameEnter the attribute value:PankajData attribute = name and its value = Pankaj
We can create a read-only attribute in the object using or .
我们可以使用或在对象中创建一个只读属性。
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 = None def get_name(self): print('get_name called') return self._name # for read-only attribute name = 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, insetattr(p, 'name', 'Pankaj')AttributeError: can't set attribute
Reference:
参考:
翻译自:
转载地址:http://bxmzd.baihongyu.com/