[Tutor] custom types question

Isr Gish isrgish at fusemail.com
Thu Feb 12 00:29:52 EST 2004



-----Original Message-----
   >From: "Thomas Clive Richards"<thomi at imail.net.nz>
   >Sent: 2/11/04 11:45:32 PM
   >To: "tutor at python.org"<tutor at python.org>
   >Subject: [Tutor] custom types question
   >
   >
   >Hi guys,
   >
   >
   >I'm building an application which uses both 2D points, and row,col indexes a 
   >lot. It would be really cool if I could create a few custom types, and then 
   >create operators for them.
   >
   >For example, a 2D point could be represented by a tuple, or list:
   >
   >>>> [23,48]
   >
   >However, I frequently need to add or subtract these points. If I try this 
   >as-is, I get this:
   >
   >>>> [10,10] + [23,20]
   >[10, 10, 23, 20]
   >
   >What I'd like to be able to do, is something like this:
   >
   >>>> [10,10] + [10,12]
   >[20,22]
   >>>>[10,10] - [20,25]
   >[-10,-15]
   >
   >I believe you do this by subclassing existing types, am I correct? I tried 
   >this:
   >>>> class point2D(list):
   >...     def __init__(self,X,Y):
   >...             self.x = X
   >...             self.y = Y
   >... 
   >>>> point2D(10,10)
   >[]
   >

I'm not an expert put lets try.
>>> class Point2D(list):
... 	def __init__(self, x, y):
... 		self.data = [x, y]
... 	def __repr__(self):
... 		return repr(self.data)
... 	def __add__(self, other):
... 		temp = self.data
... 		temp[0] += other.data[0]
... 		temp[1] += other.data[1]
... 		return self.__class__(temp[0], temp[1])
... 

Here is a test output:
>>> p = Point2D(10, 15)
>>> q = Point2D(5, 20)
>>> p + q
[15, 35]

The only thing about this is that "p" is also getting changed. I'm sure it has to do with the return of __add__ but I'm not sure what it is. Maybe someone else can help with that. But this would be a start.

   >
   >A few problems with this... It doesn't actually give me any additional 
   >functionality.. I still can't add points...
   >
   >I'm sure I've seen soem documentation somewhere about how to do this. I guess 
   >I should start bookmarking interesting pages..
   >
   >Anyway, any pointers would be very helpful, thanks ;)
   >
   >-- 
   >
   >Thomi Richards,
   >thomi at once.net.nz
   >
   >
   
All the be t,
Isr




More information about the Tutor mailing list