What I am wondering is if I have a 2nd init or something similar to create a vector. Such as what follows and if I can how do I go about implementing it?
Class vector(point): def __init___(self, point1, point2): self.i = point2.get_x() - point1.get_x() self.j = point2.get_y() - point1.get_y() self.k = point2.get_z() - point1.get_z()
def __init___(self, i, j, k): self.i = i self.j = j self.k = k
That way I can define a vector either using 2 points or if I have the vector data itself?
Well, what you want to do -- polymorphism of function signatures -- can be
implemented like this:
class vector_1(point) :
def __init__(self,*args) :
if len(args) == 2 and isinstance(args[0],point) and isinstance(args[1],point) :
self.i = args[0].get_x() - args[1].get_x()
self.j = args[0].get_y() - args[1].get_y()
self.k = args[0].get_z() - args[1].get_z()
elif len(args) == 3 : self.i,self.j,self.k = args
else : raise ValueError, "wrong arguments for instance initialization"
You can also find a nice implementation by Guido van Rossum using decorators
at Artima (look for multimethods).
However, I would prefer to avoid this sort of polymorphism because it only
obfuscates your code. IMHO, there should be exactly one clear way to initialize
an instance. Therefore, I suggest the provide a class method that serves as a
special instance factory:
class vector_2(point) : def __init__(self,i,j,k) : self.i = i self.j = j self.k = k
@classmethod def difference(cls,point1,point2) : return cls( point1.get_x() - point2.get_x(), point1.get_y() - point2.get_y(), point1.get_z() - point2.get_z() )
# how to use it: point1 = Point(4,5,6) point2 = Point(1,2,3) vec = vector_2.difference(point1,point2)
I wonder, why your vector inherits from point though. And of course, class is written lower case.
Cheers,
- harold -
-- Es ist schon längst alles gesagt worden -- aber noch nicht von jedem. -- Karl Valentin
-- http://mail.python.org/mailman/listinfo/python-list