Reputation: 49
I have below code that I have written
class Test:
def __init__(self,value):
''' Constructor. '''
self.ext_ip_address = value
def ip_address_changed(self):
with open(IP_ADDR, 'r') as ip_address:
ip_addr = ip_address.read().replace('\n','')
if not ip_address == self.ext_ip_address:
self.ext_ip_address = ip_address
print 'IP ADDR', ip_addr
print 'EXT IP ADDR', self.ext_ip_address
return True
return False
# Run following code when the program starts
if __name__ == '__main__':
test_obj = Test('')
if test_obj.ip_address_changed():
print "IP changed"
else:
print "IP constant"
Here I am reading the IP address of a machine from file (i.e. ip_addr
local variable), then I am checking whether the IP address of machine is changed from the last value (i.e. self.ext_ip_address
). Then I am trying to print the values of both variables ip_addr
and self.ext_ip_address
. For ip_addr
, I am getting the proper value. But for self.ext_ip_address
I am getting strange value as below:
IP ADDR 192.168.44.100
EXT IP ADDR <open file '/usr/local/bin/data/ip_address.dat', mode 'r' at 0xb772e230>
Please let me know what is the reason for this. Thanks in advance!!!
Upvotes: 0
Views: 63
Reputation: 8829
You mixed up ip_addr
and ip_address
in two places. ip_address
is your file, which is what you wound up printing instead of the address you had in mind.
class Test:
def __init__(self,value):
''' Constructor. '''
self.ext_ip_address = value
def ip_address_changed(self):
with open(IP_ADDR, 'r') as ip_address:
ip_addr = ip_address.read().strip() # Per VMRuiz's comment
if not ip_addr == self.ext_ip_address: # HERE
self.ext_ip_address = ip_addr # AND HERE
print 'IP ADDR', ip_addr
print 'EXT IP ADDR', self.ext_ip_address
return True
return False
Clearer variable names will prevent this problem in the future.
Upvotes: 4