Home > other >  Is there a way to use the name of an object to a list instead of the value of that object?
Is there a way to use the name of an object to a list instead of the value of that object?

Time:03-21

The best way to demonstrate is through a basic code example:

aaa = 0
bbb = 0

objects_list = [aaa,bbb,aaa,bbb]

for obj in objects_list:
    obj  = 1

print(aaa)
print(bbb)

I understand that this way when creating the loop, the list is read like this:

objects_list = [0,0,0,0]

The print Terminal is:

0
0

The expected output in the terminal prints would be:

2
2

I'd like to recreate this here but in a loop:

aaa  = 1
bbb  = 1
aaa  = 1
bbb  = 1

Is there any way to create a list with object name instead of their values?

CodePudding user response:

You can't do that as integers are immutable, but there is a way around it:

objects_list = ["aaa", "bbb", "aaa", "bbb"]   # Note that they are strings

for obj in objects_list:
    locals()[obj]  = 1

Note that this type of programming is discouraged as it will confuse future maintainers and lead to subtle and hard to find bugs.

CodePudding user response:

Python's int is immutable. What you are asking is saving a "pointer" to the list. This is impossible for a integer, but needs an object. Here is an example how objects work:

class ValueWrapper(object):
    def __init__(self, value):
        self.value = value

    def __iadd__(self, x):
        self.value  = x

    def __str__(self):
        return str(self.value)

aaa = ValueWrapper(0)
bbb = ValueWrapper(0)

objects_list = [aaa,bbb,aaa,bbb]

for obj in objects_list:
    obj  = 1

print(aaa)
print(bbb)

Above codes give results

2
2
  • Related