Introducing Python to others

David C. Ullrich dullrich at sprynet.com
Tue Mar 31 17:46:00 CEST 2009


In article 
<039360fb-a29c-4f43-b6e0-ba97fb5981a3 at z23g2000prd.googlegroups.com>,
 Mensanator <mensanator at aol.com> 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?

Yes, in the code I posted. That code was not meant to be
an example of the right way to do anything, just an
illustration of how wonderful things like __add__ can be.

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

-- 
David C. Ullrich



More information about the Python-list mailing list