Python Vector Class

jedmao picture jedmao · Mar 8, 2010 · Viewed 25k times · Source

I'm coming from a C# background where this stuff is super easy—trying to translate into Python for Maya.

There's gotta' be a better way to do this. Basically, I'm looking to create a Vector class that will simply have x, y and z coordinates, but it would be ideal if this class returned a tuple with all 3 coordinates and if you could edit the values of this tuple through x, y and z properties, somehow.

This is what I have so far, but there must be a better way to do this than using an exec statement, right? I hate using exec statements.

class Vector(object):
    '''Creates a Maya vector/triple, having x, y and z coordinates as float values'''

    def __init__(self, x=0, y=0, z=0):
        self.x, self.y, self.z = x, y, z

    def attrsetter(attr):
        def set_float(self, value):
            setattr(self, attr, float(value))
        return set_float

    for xyz in 'xyz':
        exec("%s = property(fget=attrgetter('_%s'), fset=attrsetter('_%s'))" % (xyz, xyz, xyz))

Answer

ChristopheD picture ChristopheD · Mar 8, 2010

If I understand your question correctly, you want something like this ?

class Vector(object):

    def __init__(self, x=0, y=0, z=0):
        self._x, self._y, self._z = x, y, z

    def setx(self, x): self._x = float(x)
    def sety(self, y): self._y = float(y)        
    def setz(self, z): self._z = float(z)     

    x = property(lambda self: float(self._x), setx)
    y = property(lambda self: float(self._y), sety)
    z = property(lambda self: float(self._z), setz)

This uses _x, _y and _z to (internally) store the incoming values and exposes them via the use of property (with getters, setters); I abbreviated the 'getters' using a lambda statement.

Note that in Python it would be very common to manipulate these values (say: x, y, z) on the object itself directly (I guess you want ensure the explicit float casts?)