It seems without explicit initialization, the lists and hashs of different instances of the same class gets the same memory address. Is this correct?
#!/usr/bin/env python3
class DataManager:
def __init__(self, name=[], value={}):
self.parm_name = name
self.parm_value = value
pass
def add_param(self, name, value):
self.parm_name.append(name)
self.parm_value[name] = float(value)
if __name__ == "__main__":
dm1 = DataManager()
dm2 = DataManager()
print("Address of dm1: %s" % hex(id(dm1)))
print("Address of dm2: %s" % hex(id(dm2)))
print("Address of dm1.parm_name: %s" % hex(id(dm1.parm_name)))
print("Address of dm2.parm_name: %s" % hex(id(dm2.parm_name)))
dm1.parm_name.append("a")
dm2.parm_name.append("b")
print("dm1.parm_name: " + str(dm1.parm_name))
print("dm2.parm_name: " + str(dm2.parm_name))
Below is the executing result:
Address of dm1: 0x7f20d9167f28
Address of dm2: 0x7f20d9167f98
Address of dm1.parm_name: 0x7f20d914bb08
Address of dm2.parm_name: 0x7f20d914bb08
dm1.parm_name: ['a', 'b']
dm2.parm_name: ['a', 'b']
What is really strange to me, that the address of dm1.parm_name is the same as that of dm2. And append actually added to the same list.
If I change the dm1 and dm2 definition as below, it will be working as expected:
dm1 = DataManager([], {})
dm2 = DataManager([], {})
Very strange, isn't it? Could anyone tell me why? Many thanks~
I also tried in Python2, the same result. versions below:
$ python3 --version
Python 3.5.0
$ python2 --version
Python 2.7.5