在python类中更新类似名称的属性

时间:2016-11-28 14:33:08

标签: python class setattribute

我想更新我的类似名称属性,但是我收到错误:

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))

2 个答案:

答案 0 :(得分:1)

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))

答案 1 :(得分:1)

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

中清楚地看到
  

[...]参数是对象,字符串和任意值。该字符串可以命名现有属性或新属性。如果对象允许,该函数会将值分配给属性。例如,setattr(x,&#39; foobar&#39;,123)相当于x.foobar = 123。

所以使用:

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

而不是:

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