[Tutor] custom types question

Thomas Clive Richards thomi at imail.net.nz
Thu Feb 12 01:48:17 EST 2004


>
> 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.
>

Ahaaa... that's a lot better...

so we can add a __subtract__ as well I guess?

something like:
	def __subtract__(self,other):
		temp = self.data
		temp[0] -= other.data[0]
		temp[1] -= other.data[0]
		return self.__class__(temp[0],temp[1])

looks good to me ;)

Now we just need to fix the rather strange behaivour with the other 
variable...

ahh.. just an idea.. is this happening because we're not really copying the 
other data? would this fix it?

	def __subtract__(self,other):
		temp = self.data[:]		#<-----change here!
		temp[0] -= other.data[0]
		temp[1] -= other.data[0]
		return self.__class__(temp[0],temp[1])

lets see:

>>> 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])
... 
>>> a = point2D(2,3)
>>> b = point2D(22,33)
>>> a + b
[24, 36]
>>> a
[2, 3]
>>> b
[22, 33]


yes!!!

that's exactly what I need..

Thanks a lot for your help.. most appreciated ;)

-- 

Thomi Richards,
thomi at once.net.nz




More information about the Tutor mailing list