dict as class property seems to be same for all instances

  python

I recognize strange behavior in my code. I extract some testcode to demonstrate:

class A:
    def __init__(self):
        super().__init__()
        self.mystr = 'A'
        self.mydict['key'] = 'value'

class B(A):
    mystr = 'B'
    mydict = {}
    def __init__(self, name):
        print(name, 'mystr (before)', self.mystr)
        print(name, 'mydict (before)', self.mydict)
        super().__init__()
        print(name, 'mystr (after)', self.mystr)
        print(name, 'mydict (after)', self.mydict)

if __name__ == '__main__':
    b1 = B('b1')
    b2 = B('b2')

The output is:

b1 mystr (before) B
b1 mydict (before) {}
b1 mystr (after) A
b1 mydict (after) {'key': 'value'}
b2 mystr (before) B
b2 mydict (before) {'key': 'value'}  // <- I expect this to be {}
b2 mystr (after) A
b2 mydict (after) {'key': 'value'}

The property mystr works as I expected. For the second instance b2 it is ‘B’ as it was initialized. But the property mydict is not initialized correct for the second instance and contains the key/value pair:

b2 mydict (before) {‘key’: ‘value’}

I know that there a mutable and immutable variables in Python and that the first one are hold by reference. But I can explain, why my code is not working as expected.

Can somebody give me a hint?

Source: Python Questions

LEAVE A COMMENT