I love vector classes with operator overloading... I couldn't stand to code without them (even though in python, it means there's probably a lot of object allocation and function calls for simple vector math, wasting performance). Code is just so much shorter & more readable with them. I know that I pay for it in performance to use them, and I know the one I use isn't the best performing one... I'll just wait to care about that when it's a real problem.
I posted the one in the library I use to the cookbook, I figure to help get the ball rolling On 8/11/06, Nelson, Scott <[EMAIL PROTECTED]> wrote:
#1 - Do you store the vector components internally as self.x and self.y or as a tuple? Or subclass the vector class from a tuple? If you use self.x and self.y, what is an efficient way to pass this as a tuple to pygame functions?
I don't think this really matters as long as you provide a list interface, and your internal functions (like operators) take advantage of whatever your internal structure is. We thought that accessing as .x and .y was really important, so we provided both interfaces (indexed access and x/y), although internally we use a two element list as a property on the class, so the representation doesn't really map to either interface directly. ...As far as subclassing from a tuple, I don't think I really looked into that, might be a great way to go... the idea of the vector object being immutable is probably actually a good idea - just because you may pass a vector in as a function argument and not want it to change... that way the vector is more like passing in two args, in that you can't change the callee's data
#2 - Do you store the values as ints (making it easier to pass to Pygame) or floats (more accurate vector math, but need to cast to int before passing to pygame functions that require a tuple of ints?). Or do you not even care and just let duck-typing do it stuff?
I say duck-typing is the way to go. while it's true that dividing integer vectors by integer vectors could maybe have unexpected results by having integer results, dividing by vectors is such a rare case, It doesn't bug me in the least. Plus it feels like the pythonic thing to do
So, after using my 2D vect class for awhile, I wasn't sure if I had taken the best approach originally. Currently, my vector class stores floats in self.x and self.y and I have 2 methods for returning tuples as follows:
I say let it just be a list (by that I mean make sure __len__ __getitem__ and __setitem__ work) rather than bother with conversion routines like that
def AsIntTuple(self): '''Cast values to int. Useful for Pygame''' return((int(self.x), int(self.y)))
So why is a tuple containing int's specifically so useful for pygame? is it to make sure you pass ints to blit?