Unexpected return value from __add__

Magnus Lycka magnus at thinkware.se
Wed Sep 26 01:34:55 CEST 2001


Thank's Piet and Marc, as usual bugs are trivial once
you find them... :)

piet at cs.uu.nl wrote:
> 
> >>>>> 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 '192.0.1.1' 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> 192.0.1.1
> 
> 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

-- 
Magnus Lyckå | Älvans väg 99 | magnus at thinkware.se | tel: 070-582 80 65
Thinkware AB | 907 50  UMEÅ  | www.thinkware.se    | fax: 070-612 80 65



More information about the Python-list mailing list