[Tutor] custom types question

SSokolow from_python_tutor at SSokolow.com
Thu Feb 12 00:12:17 EST 2004


Thomas Clive Richards wrote:

>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)
>>>>        
>>>>
>[]
>
>
>A few problems with this... It doesn't actually give me any additional 
>functionality.. I still can't add points...
>
>  
>
Would a function in the class be good enough for you?
Something like this?

 >>> class point2D(list):
...     def __init__(self,X,Y):
...         self.x = X
...         self.y = Y
...     def add(self,p2D):
...         self.x += p2D.x
...         self.y += p2D.y
...        
 >>> a = point2D(10,10)
 >>> b = point2D(5,10)
 >>> a.add(b)
 >>> a.x
15
 >>> a.y
20

>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 ;)
>
>  
>

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20040212/8b1b86e2/attachment.html


More information about the Tutor mailing list