[Author Prev][Author Next][Thread Prev][Thread Next][Author Index][Thread Index]

RE: [pygame] When to use a constant



You could use Object.X and Object.Y, and (for velocity) Object.XVelocity
or Object.DX.  If you use a little __getattr__ and __setattr__ magic,
you can still store the actual position and velocity components in your
arrays.  

(If it were me, I think I would just use Object.X and so on directly,
unless I could save a *lot* of duplicate code by looping over the two
axes)

The code could look like this:

class Thingy:
    def __init__(self, Position):
        self.Position = Position
    def __getattr__(self, Name):
        if Name=="X":
            return self.Position[0]
        elif Name=="Y":
            return self.Position[1]
        else:
            return self.__dict__[Name]
    def __setattr__(self, Name, Value):
        if Name=="X":
            self.Position[0] = Value
        elif Name=="Y":
            self.Position[1] = Value
        else:
            self.__dict__[Name] = Value

Dog = Thingy([10,4])
print Dog.X # prints 10
Dog.Y = 20
print Dog.Position # prints [10, 20]


> -----Original Message-----
> From: owner-pygame-users@seul.org 
> [mailto:owner-pygame-users@seul.org] On Behalf Of Jon Doda
> Sent: Tuesday, May 11, 2004 7:03 AM
> To: pygame-users@seul.org
> Subject: [pygame] When to use a constant
> 
> 
> 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?
> 
> -- 
> Jon Doda
>