更新 python class 中的相似名称属性

Update similar name atributes in python class

我想更新我的相似姓名属性,但出现错误:

Traceback (most recent call last):
  File "python", line 12, in <module>
NameError: name 'name_0_' is not defined

这是我的代码:

class Test:
    name_0_1 = 0 
    name_0_2 = 0   
    name_0_3 = 0 
    name_0_4 = 0


my_object = Test()
my_list_value = range(1,8)

for i in my_list_value:
  print(setattr(my_object, name_0_ + str(i), i))

setattr第二个参数必须是字符串:

class Test:
    name_0_1 = 0 
    name_0_2 = 0   
    name_0_3 = 0 
    name_0_4 = 0


my_object = Test()
my_list_value = range(1,8)

for i in my_list_value:
  print(setattr(my_object, 'name_0_' + str(i), i))

使用setattr() 需要您传递一个字符串作为第二个参数。这可以在 Python documentation for setattr():

中清楚地看到

[...] The arguments are an object, a string and an arbitrary value. The string may name an existing attribute or a new attribute. The function assigns the value to the attribute, provided the object allows it. For example, setattr(x, 'foobar', 123) is equivalent to x.foobar = 123.

所以使用:

setattr(my_object, 'name_0_' + str(i), i)

而不是:

setattr(my_object, name_0_ + str(i), i)