I am trying to add to a python class an alternate constructor who initialise an object from a config file. I use the following code, who according to my understanding of @classmethod should do the job.
class Dummy:
_list = []
def __init__(self, list=None):
if list is not None:
self._list = list
@classmethod
def from_config(cls, config):
temp = Dummy()
for c in config:
temp._list.append(c)
return temp
def __str__(self):
return '\n'.join([str(c) for c in self._list])
t = Dummy.from_config([1, 2])
t2 = Dummy.from_config([3, 4])
print(t)
print("---")
print(t2)
This print:
1234
---
1234
I don't understand why ? I was expecting the first class get 12 and the second 34
Edited:
Based on reply received I edited the code like this to remove class variable and to always set instance variable (self._list) in constructor. This still show the same issue:
class Dummy:
def __init__(self, list=[]):
self._list = list
@classmethod
def from_config(cls, config):
temp = Dummy()
for c in config:
temp._list.append(c)
return temp
def __str__(self):
return '\n'.join([str(c) for c in self._list])
t = Dummy.from_config([1, 2])
t2 = Dummy.from_config([3, 4])
print(t)
print("---")
print(t2)
I also see that if from the from_config method I call:
temp = Dummy([])
instead of:
temp = Dummy()
it works as expected. I don't understand why as for me both variant do the same as default value for constructor parameter is [].