0

In Python why does the class

class MyClass():
    def __init__(self, _my_dict={}):
        self.my_dict = _my_dict

have the following very strange and undesired behaviour:

>>> a = MyClass()
>>> a.my_dict['greet'] ="hallo"
>>> b = MyClass()
>>> b.my_dict['greet'] ="ciao"
>>> 
>>> print(a.my_dict)
{'greet': 'ciao'}
>>> print(b.my_dict)
{'greet': 'ciao'}

Note: I know I can fix this by using None as _my_dict default in the __init__ method:

class MyClass():
    def __init__(self, _my_dict=None):
        if _my_dict is None:
            self.my_dict = {}
        else:
            self.my_dict = _my_dict

So the problem lies clearly with the '{}' as the default for _my_dict: It seems to refer in both instantiations to the same object. But why is this so? And is there a tighter solution than mine with the cumbersome if statement?

halloleo
  • 9,216
  • 13
  • 64
  • 122

0 Answers0