Access to value of variable with dynamic name

Variable names are a terrible way to relate pieces of information. There is nothing linking man_pos and man_vel except that they both happen to start with man. Other than that they are totally separate. Python has better ways of bundling elements like these together.

In this case, man and car should be objects with attributes pos and vel.

class Thing:
    def __init__(self, pos, vel):
        self.pos = pos
        self.vel = vel

# assume that both men and cars move only in one dimension
man = Thing(10, 2)   
car = Thing(100, -5)

Then your loop is simply:

for item in [car, man]:
    print(item.pos, item.vel)

Do not do it the way you’re trying to do it. It will only lead to tears — if not yours, then of the people who have to look at your code.

Leave a Comment