__iadd__ and __isub__ map to += and -= but don't return result

Anthra Norell anthra.norell at tiscalinet.ch
Fri Apr 8 11:04:43 EDT 2005


Hi!

If I am missing a point here, what could it be? Watch the hot spots (***)

Frederic


#############################################################################


# Python 2.4, Windows ME

X = 0, Y = 1  

class Vertex (list):
   def __init__ (self, *coordinates): self [:] = list (coordinates [0:2])
   def __add__ (self, V):  return Vertex (self [X] + V [X], self [Y] + V [Y])
   def __iadd__ (self, V): self [X] += V [X]; self [Y] += V [Y]


>>> V1 = Vertex (1, 2)
>>> V2 = Vertex (4, 6)

>>> V1 + V2
[5, 8]            # OK

>>> V1 += V2      # ***
V1                # ***   
                  # *** died ?
>>> print V1
None              # *** V1 died !
>>> V2
[5, 8]            # V2 is fine

   # Adding three traces to follow the state of self

   def __iadd__ (self, V):
      print 'A', self
      self [X] += V [X]
      print 'B', self
      self [Y] += V [Y]
      print 'C', self

>>> V1 += V2
A [1, 2]
B [5, 2]
C [5, 8]          # *** self is still OK when method terminates.
                  # *** Also shows that operator += did call __iadd__, 
                  # *** (though the 2.4 doc no longer mentions it)


# Explicit call works fine

>>> V1.__iadd__ (V2)
A [1, 2]
B [5, 2]
C [5, 8]

>>> V1 
[5, 8]     <<<< OK !!!

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20050408/701ec7fa/attachment.html>


More information about the Python-list mailing list