[Tutor] custom types question

Thomas Clive Richards thomi at imail.net.nz
Fri Feb 13 05:03:41 EST 2004


On Thursday 12 February 2004 20:44, Gregor Lingl wrote:
>
> 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 ...


hmm.. I'm not sure I understand this... I'm only beginning ;)

For one, I'm still having trouble getting my mind around the list logic (or 
whatever it's called.. the "[x*y for x,y in zip(self,other)]" bits..

I'll rewrite it using errr.. normal logic, and see if I can make sense from 
it..

It might be worth someone writing a 3rd party module with additional types? It 
seems like these things muct be used quite frequently...

-- 

Thomi Richards,
thomi at once.net.nz




More information about the Tutor mailing list