0

Looking at code below we see 2 instances of the same class. While we change a mutable property we actually change it to both instances. I find it tricky. Can anyone explain why does it act like this?

class MyClass:
    name: str = None
    dic: Dict[str, str] = {}


instance_1 = MyClass()
instance_2 = MyClass()
instance_1.name = ':)'
instance_1.dic['key'] = 'value'
print(instance_2.name)  # as expected prints None for immutable type str
print(instance_2.dic['key'])  # as unexpected prints value, for mutable type dic
Michał Lis
  • 461
  • 1
  • 6
  • 19
  • 1
    Use `__init__` to give each class instance its own, private copy of the instance variables, particularly `dic`. – Tom Karzes May 11 '19 at 14:14
  • 1
    It looks like you are trying to declare a dataclass but forgot the decorator. `@dataclass class MyClass: ...`. – chepner May 11 '19 at 14:14

0 Answers0