Introducing Python to others

Scott David Daniels Scott.Daniels at Acm.Org
Thu Mar 26 15:58:56 EDT 2009


Mensanator wrote:
> On Mar 26, 11:42 am, "andrew cooke" <and... at acooke.org> wrote:
>> ...
>> that's cute, but if you show them 2.6 or 3 it's even cuter:
>>
>>>>> from operator import add
>>>>> class Vector(list):
>> ...   def __add__(self, other):
>> ...     return map(add, self, other)
>> ...>>> x = Vector([1,2])
>>>>> x+x
>> [2, 4]
> 
> What would you have to do to make this work?
> 
>>>> x+x+x      # expecting [3,6]
> [2, 4, 1, 2]
> 

     class Vector(list):
         def __add__(self, other):
             return type(self)(x + y for x, y in zip(self, other))
         def __sub__(self, other):
             return type(self)(x - y for x, y in zip(self, other))
         def __repr__(self):
             return '%s(%s)' % (
                     type(self).__name__, list.__repr__(self))

     x = Vector([1,2])
     x + x + x

--Scott David Daniels
Scott.Daniels at Acm.Org



More information about the Python-list mailing list