[Author Prev][Author Next][Thread Prev][Thread Next][Author Index][Thread Index]
Re: [pygame] When to use a constant
Jon Doda schreef:
> I'm working on a simple 2D physical simulation. The various simulation
> objects have position and velocity attributes that store the x and y
> components in a list. So, to get the y component of velocity for some
> object you do something like "sim_object.velocity[1]".
>
> Recently I've been tempted to define constants for the index values of
> the lists, so I'd have X = 0, and Y = 1, and the code from above would
> be "sim_object.velocity[Y]". It would make reading the simulation code
> somewhat easier (no more converting 0 to x and y to 1 in my head) but it
> would add a level of indirection, which could be confusing.
>
> So, the question is, would using constants in this way be a reasonable
> thing to do, or is it bad practice?
I usually avoid the problem by defining a class. Semantically, a list is
not logical for velocity: why would velocity be a list, or a sequence at
all? You can do:
>>> class Velocity:
... x = y = 0
...
>>> my_v = Velocity()
>>> my_v.x += 6
>>> my_v.y -= 2*my_v.x
>>> my_v.x, my_v.y
(6, -12)
I think this is the most readable solution.
yours,
Gerrit.
--
Weather in Twenthe, Netherlands 11/05 15:25:
15.0°C Few clouds mostly cloudy wind 6.3 m/s WNW (57 m above NAP)
--
Ervaringen met het Syndroom van Asperger:
http://topjaklont.student.utwente.nl
Socialistische Partij:
http://www.sp.nl/