Introducing Python to others

andrew cooke andrew at acooke.org
Thu Mar 26 17:42:01 CET 2009


David C. Ullrich wrote:
> In article <mailman.2701.1238060157.11746.python-list at python.org>,
>  "Paddy O'Loughlin" <patrick.oloughlin 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






More information about the Python-list mailing list