Python setattr()

时间:2020-02-23 14:43:18  来源:igfitidea点击:

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

Python setattr()

Python setattr()函数语法为:

setattr(object, name, value)

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

输入参数是将设置属性的"对象","名称"是属性名称,"值"是属性值。

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

class Data:
  pass

d = Data()

d.id = 10

print(d.id)

setattr(d, 'id', 20)
print(d.id)

输出:

10
20

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

那么使用setattr()函数的好处其中呢?

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

用户输入的Python 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))

输出:

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

Python setattr()异常

我们可以使用属性函数或者属性装饰器在对象中创建一个只读属性。

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

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', 'hyman')

输出:

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