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.
Just use the globals() dictionary, with key as your variable names. The value for these keys would be the actual value of these variables.
car_pos = 1; man_pos = 10
car_vel = 100; man_vel = 5
for elm in ['car', 'man']:
elm_pos = elm + '_pos'
elm_vel = elm + '_vel'
print(globals()[elm_pos], globals()[elm_vel])
Agree with everything that kindall said. However, you can try named tuple to go the non dictionary route...
from collections import namedtuple
data = namedtuple('data',('pos','vel'))
car = data(1,100)
man = data(10,5)
for elm in (car,man):
print(elm.pos,elm.vel)