[Tutor] custom types question

Gregor Lingl glingl at aon.at
Thu Feb 12 02:44:14 EST 2004



Isr Gish schrieb:

>
>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]
>
>  
>
This has the property that it changes p, which
may be considered a disadvantage:

 >>> p=Point2D(10,15)
 >>> q=Point2D(5,20)
 >>> p
[10, 15]
 >>> q
[5, 20]
 >>> p+q
[15, 35]
 >>> p
[15, 35]
 >>>

I recently asked for help concerning a similar problem and finally came
up with a Vector class as a subclass of class tuple, which looks like this:

class Vec(tuple):

    def __new__(cls, *args):
        return tuple.__new__(cls, args)

    def __add__(self, other):
        return Vec(*[x+y for (x,y) in zip(self,other)])

    def __mul__(self, other):
        if isinstance(other, Vec):
            return sum([x*y for x,y in zip(self,other)])
        else:
            return Vec(*[x*other for x in self])

# ...  and many more methods
Here, for instance, __repr__ doesn't need to be defined
as it is inherited from tuple ...
Moreover you have the advantage, that many convenient
features of the tuple class, as slicing, tuple-unpacking etc.
also work for Vec ...

Hope this helps, just as a suggestion ...

Gregor




More information about the Tutor mailing list