python - Access to value of variable with dynamic name -
i found several topics discussed dynamical creating of single variables in loops bad practice , better use dictionary.
in case don't need create them dynamically, want access them in loop.
i don't want use dictionary them, because these variables used in lot of places in code, , in 1 place need such dynamic access.
idea example:
car_pos = 1; man_pos = 10 car_vel = 100; man_vel = 5 elm in ['car', 'man']: elm_pos = elm + '_pos' elm_vel = elm + '_vel' # want values of elements such names here print(elm_pos, elm_vel) # desired output: # (1, 100) # (10, 5)
variable names terrible way relate pieces of information. there nothing linking man_pos , man_vel except both happen start man. other totally separate. python has better ways of bundling elements these together.
in case, man , car should objects attributes pos , vel.
class thing: def __init__(self, pos, vel): self.pos = pos self.vel = vel # assume both men , cars move in 1 dimension man = thing(10, 2) car = thing(100, -5) then loop simply:
for item in [car, man]: print(item.pos, item.vel) do not way you're trying it. lead tears -- if not yours, of people have @ code.
Comments
Post a Comment