0

I have the following code in python:

from typing import Dict, Optional

class UpperClass:
    def __init__(self, dict: Optional[Dict] = {}):
        self._dict = dict

    def __str__(self):
        return ",".join([f"{key}-{value}" for key, value in self._dict.items()])


class LowerClass(UpperClass):
    def __init__(self, *args):
        super().__init__(*args)
        self._dict["Hello"] = "World"

upper_class = UpperClass()
print(upper_class)
lower_class = LowerClass()
print(lower_class)

### Now the confusion
print(upper_class)
Entry: 
Entry: Hello-World
Entry: Hello-World

I define a fresh UpperClass object upper_class. The parameter dict does not exist and so it is newly created and empty as expected. Now I define a fresh LowerClass object lower_class where dict is filled. Again, the output is as expected.

Now the question: Why has this changed upper_class?

I would have thought that I have two separated objects upper_class and lower_class with separated member variable objects _dict. But this does not seem to be the case. Some reference stuff is happening. This makes me nervous ...

0 Answers0