Introducing Python to others

Peter Otten __peter__ at web.de
Thu Mar 26 19:43:17 CET 2009


Mensanator wrote:

> On Mar 26, 11:42 am, "andrew cooke" <and... at acooke.org> wrote:
>> David C. Ullrich wrote:
>> > In article <mailman.2701.1238060157.11746.python-l... at python.org>,
>> > "Paddy O'Loughlin" <patrick.olough... at gmail.com> wrote:
>>
>> > Here's my favorite thing about Python (you'd of course
>> > remark that it's just a toy example, doing everything
>> > in as dumb but easily understood way as possible):
>>
>> > x=[1,2]
>>
>> > print x+x
>>
>> > class Vector():
>> > def __init__(self, data):
>> > self.data = data
>> > def __repr__(self):
>> > return repr(self.data)
>> > def __add__(self, other):
>> > return Vector([self.data[0]+other.data[0],
>> > self.data[1]+other.data[1]])
>>
>> > x = Vector([1,2])
>>
>> > print x+x
>>
>> 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]
>>
>> andrew
> 
> Mind if I ask a question? In DU's code, both operands have to
> be instances of the Vector class?
> 
>>>> x = Vector([1,2])
>>>> x+x
> [2, 4]
>>>> x+[3,3]
> 
> Traceback (most recent call last):
>   File "<pyshell#60>", line 1, in <module>
>     x+[3,3]
>   File "<pyshell#55>", line 7, in __add__
>     return SV([self.data[0]+other.data[0],self.data[1]+other.data[1]])
> AttributeError: 'list' object has no attribute 'data'
> 
> 
> Whereas with your version, "other" just has to be an iterable.
> 
>>>> x = Vector([1,2])
>>>> x+x
> [2, 4]
>>>> x+[3,3]
> [4, 5]
>>>> x+(9,9)
> [10, 11]
>>>> x+{3:4,4:9}
> [4, 6]
> 
> Although it does require the same number of elements (because that's
> required by map and could be changed if necessary).
> 
>>>> x+[3,3,3]
> 
> Traceback (most recent call last):
>   File "<pyshell#71>", line 1, in <module>
>     x+[3,3,3]
>   File "<pyshell#62>", line 3, in __add__
>     return map(add,self,other)
> TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'
> 
> 
> What would you have to do to make this work?
> 
>>>> x+x+x      # expecting [3,6]
> [2, 4, 1, 2]

Use itertools.imap() which stops when the shortest sequence is exhausted and
have Vector.__add__() return a Vector:

>>> from operator import add
>>> from itertools import imap
>>> class Vector(list):
...     def __add__(self, other):
...             return Vector(imap(add, self, other))
...
>>> a = Vector([1,2,3])
>>> a + [10, 20]
[11, 22]
>>> a + a + a
[3, 6, 9]
>>>

Peter



More information about the Python-list mailing list