Class, object question.
Ian Sparks
Ian.Sparks at etrials.com
Tue Apr 5 17:22:23 EDT 2005
Use the *args positional-argument to catch all the positional arguments in the constructor then test them to see what you have and call a kind of sub-init based on that :
class Point:
def __init__(self,x,y,z):
self.x = x
self.y = y
self.z = z
class Vector:
def __init__(self,*args):
if len(args) == 3:
self.setFromValues(args)
elif len(args) == 2:
if isinstance(args[0],Point):
self.setFromPoints(args)
else:
raise "Incorrect constructor"
print self.i,self.j,self.k
def setFromValues(self,args):
self.i,self.j,self.k = args
def setFromPoints(self,args):
self.i = args[1].x - args[0].x
self.j = args[1].y - args[0].y
self.k = args[1].z - args[0].z
v = Vector(1,2,3)
p1 = Point(2,2,2)
p2 = Point(4,4,4)
v2 = Vector(p1,p2)
Hope this helps.
-----Original Message-----
From: Jeffrey Maitland [mailto:maitj at vianet.ca]
Sent: Tuesday, April 05, 2005 10:04 AM
To: python-list at python.org
Subject: Class, object question.
Hello folks,
The question I am having is something like this.
# ignore the precursing .... I am using them for easy message formatting
from point import *
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()
# methods of vector. Defined here.
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?
Thanks in advance
Jeff
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20050405/f781b9b6/attachment.html>
More information about the Python-list
mailing list