Will McGugan wrote: > I am writting a Vector3D class as a teaching aid (not for me, for > others), and I find myself pondering over the __init__ function. I want > it to be as easy to use as possible (speed is a secondary > consideration). > > Heres the __init__ function I have at the moment. > > class Vector3D(object): > > __slots__ = ('x', 'y', 'z') > > def __init__(self, x_or_iter=None, y=None, z=None): > > if x_or_iter is None: > self.x = self.y = self.z = 0 > elif z is None: > it = iter(x_or_iter) > self.x = float(it.next()) > self.y = float(it.next()) > self.z = float(it.next()) > else: > self.x = float(x_or_iter) > self.y = float(y) > self.z = float(z) > > A Vector3D can be constructed in 3 ways. If no parameters are given it > assumes a default of (0, 0, 0). If one parameter is given it is assumed > to be an iterable capable of giving 3 values. If 3 values are given > they are assumed to be the initial x, y, z. >
here's a slightly different approach: class Vector3D(object): __slots__ = ('x', 'y', 'z') def __init__(self, X1=None, X2=None, X3=None): if X3 is not None: #assume 3 numbers self.x = X1 self.y = X2 self.z = X3 else: X1 = X1 or (0,0,0) X2 = X2 or (0,0,0) self.x = X1[0] - X2[0] self.y = X1[1] - X2[1] self.z = X1[2] - X2[2] def __getitem__(self, index): return getattr(self,self.__slots__[index]) def __str__(self): return '(%s, %s, %s)' % (self.x, self.y, self.z ) u = Vector3D() print u u = Vector3D(3,4,5) print u u, v = Vector3D( [1,2,3] ), Vector3D( (3,2,1) ) print u, v w = Vector3D( u,v ) print w w = Vector3D( u, (2,2,2)) print w (0, 0, 0) (3, 4, 5) (1, 2, 3) (3, 2, 1) (-2, 0, 2) (-1, 0, 1) Gerard -- http://mail.python.org/mailman/listinfo/python-list