0

I have a number of objects with a similar name format, e.g. max_A, max_B, max_C etc. Given the value of a certain object ID, I'd like to change the value of the object named max_ID (let's say increment by 1, assuming the object already stores an int).

E.g. if ID = 'A' then I'd like to execute max_A += 1, but if ID = 'Q' then I'd like max_Q += 1.

I know I can use eval('max_'+ID) to get the value of max_ID, but how can I change the value?

1
  • Oh, wait, would exec() do it? Commented Dec 20, 2021 at 12:00

2 Answers 2

0

You can represent the objects like bellow and use endswith function to find the appropriate object to be incremented:

class Data:
    def __init__(self, name, value):
        self.name = name
        self.value = value


max_A = Data("max_A", 1)
max_B = Data("max_B", 2)
max_C = Data("max_C", 3)

obj_list = [max_A, max_B, max_C]


def increment_object_value(ending: str, objects: list):
    for obj in objects:
        if obj.name.endswith(ending):
            obj.value += 1


increment_object_value("A", obj_list)
increment_object_value("B", obj_list)
increment_object_value("C", obj_list)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the answer. But I think exec() would do it much simpler
0

Using exec:

exec('max_'+ID+' += 1')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.