git-e git-e - 10 months ago 52
Python Question

Update similar name atributes in python class

I want to update my similar name atributes but I get an error:

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

Here is my code:

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

Answer Source

Using setattr() requires you to pass a string as the second parameter. This can clearly be seen in the 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.

So use:

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

Instead of:

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