Introducing Python to others

David C. Ullrich dullrich at sprynet.com
Tue Mar 31 11:56:44 EDT 2009


In article <TM6dnZxRVIQ0QFbUnZ2dnUVZ_rmdnZ2d at pdx.net>,
 Scott David Daniels <Scott.Daniels at Acm.Org> wrote:

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

Question: I would have thought it would be 

      return type(self)([x + y for x, y in zip(self, other)])

What's this thing that looks like a list comprehension but isn't?

Comment:

I didn't mean to start a big deal, but as long as it's started:
Of course returning that list as in Andrew's example is not what
we want. Someone said we should return a Vector instead. That's
probably what the demo should do, but in stuff like this that
I actually _use_ I tend to do something like what you do here
(with very different spelling, since type(self) wouldn't work
in the bad old days.) The reason of course being that we want
subclasses to return instances of the subclass automatically.

On the other hand I have this vague feeling that explicitly
inspecting the type like this is "wrong" - I've always wondered
whether this is the "right" way to do it. ???

>          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

-- 
David C. Ullrich



More information about the Python-list mailing list