Unexpected return value from __add__
Magnus Lycka
magnus at thinkware.se
Fri Sep 7 06:19:41 EDT 2001
The code below puzzles me. Am I just blind, or is there something
really strange here...
The code below is a small test case for the problem. Don't
expect it to make any sense... Anyway, I have an IP address
stored as a long, and presented as '192.0.1.1' etc. I have
an __add__ method where I can add an integer value to an IP
address, so that I ought to get:
>>> a = IPAddr((192,0,0,0))
>>> b = a + 257
>>> print b
192.0.1.1
What actually happens is that I get an object of the right
class back, but not with the right value. The internal long
has the value 0! But if I remove the # in __add__, I see a
printout of just the value I expected! Somehow it seems to
get lost when I return it! Some strange scope thingie???
I'm using ActivePython build 2.1.211
--
class IPAddr:
def __init__(self,addr):
if type(addr) == type(0L):
self.addr = addr
else:
self.addr = 0L
for digit in addr:
self.addr = 256*self.addr+digit
def __str__(self):
res = []
while self.addr:
self.addr, digit = divmod(self.addr,256)
res.append(str(digit))
res.reverse()
return ".".join(res)
def __add__(self, number):
newAddress = self.addr+number
new = IPAddr(newAddress)
#print "New IP", new, new.__class__
return new
import unittest
class IPAddrTest(unittest.TestCase):
def testAdd(self):
a = IPAddr((192,0,0,0))
b = a + 257
# Check that a stays the same
assert str(a) == "192.0.0.0", "Expected '192.0.0.0', \
got '%s'" % str(a)
# Check that we get the right type back
assert isinstance(b,IPAddr)
# Check that we get correct value
assert str(b) == "192.0.1.1", "Expected '192.0.1.1', \
got '%s' (%d)" % (str(b), b.addr)
unittest.main()
--
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