Short, crazy example: list-derived class, with __iadd__

Marshall T. Vandegrift llasram at gmail.com
Wed Aug 29 17:19:22 EDT 2007


Moon <no.email.here at zombo.com> writes:

> class Vec(list):
>     def __init__(self):
>         list.__init__(self, [0.0, 0.0])
>
>     def __iadd__(self, other):
>         assert isinstance(other, Vec)
>         self[0] += other[0]
>         self[1] += other[1]
>         print "right now, v is: ", self, " as you'd expect"
          return self
>
>
> v = Vec()
> w = Vec()
> w[0] = 1.0
> w[1] = 2.0
> print "v starts:", v
>
> print "(w is:", w, " which is fine)"
>
> v += w
>
> print "(w still is:", w
>
  print "after iadd, v: ", v

>
> # - running it: 

v starts: [0.0, 0.0]
(w is: [1.0, 2.0]  which is fine)
right now, v is:  [1.0, 2.0]  as you'd expect
(w still is: [1.0, 2.0]
after iadd, v:  [1.0, 2.0]

-Marshall




More information about the Python-list mailing list