Unexpected return value from __add__

piet at cs.uu.nl piet at cs.uu.nl
Fri Sep 7 13:23:54 CEST 2001

>>>>> Magnus Lycka <magnus at thinkware.se> (ML) writes:

ML> The code below puzzles me. Am I just blind, or is there something
ML> really strange here...

ML> The code below is a small test case for the problem. Don't
ML> expect it to make any sense... Anyway, I have an IP address
ML> stored as a long, and presented as '' etc. I have
ML> an __add__ method where I can add an integer value to an IP
ML> address, so that I ought to get:

>>>> a = IPAddr((192,0,0,0))
>>>> b = a + 257
>>>> print b

ML> What actually happens is that I get an object of the right
ML> class back, but not with the right value. The internal long
ML> has the value 0! But if I remove the # in __add__, I see a
ML> printout of just the value I expected! Somehow it seems to
ML> get lost when I return it! Some strange scope thingie???

ML>     def __str__(self):
ML>         res = []
ML>         while self.addr:
ML>             self.addr, digit = divmod(self.addr,256)

Your __str__ modifies self.addr and thus destroys the value (until it is 0)
Piet van Oostrum <piet at cs.uu.nl>
URL: http://www.cs.uu.nl/~piet [PGP]
Private email: P.van.Oostrum at hccnet.nl

More information about the Python-list mailing list