Search code examples
pythonclassdictionaryfieldmemory-address

Updating Python Class fields


This is a basic question that can shed some light on how class fields are updated. I came across the following situation:

class MyClass():
    def __init__(self):
        self.a=0
        self.my_dict={'a':self.a}

c=MyClass()
print('c.a=', c.a)
print('c.my_dict[\'a\']=', c.my_dict['a'])
c.my_dict['a']=1
print('c.a=', c.a)
print('c.my_dict[\'a\']=', c.my_dict['a'])

Results:

c.a= 0
c.my_dict['a']= 0
c.a= 0
c.my_dict['a']= 1

c.a has the same value. Why? Shouldn't c.a reference the same location in memory as c.my_dict['a']?


Solution

  • If, after your code, you look at the variables in your class, hopefully it clarifies things:

    >>> vars(c)
    {'a': 0, 'my_dict': {'a': 1}}
    

    When you assign self.my_dict = {'a': self.a}, you read the current value of a, then make a dict {'a': that_value}. There is no reference to the variable a.

    If you wanted to store such a reference, you could do something like the following:

    class MyClass():
        def __init__(self):
            self.a = [0]
            self.my_dict = {'a': self.a}
    
    c = MyClass()
    >>> vars(c)
    {'a': [0], 'my_dict': {'a': [0]}}
    
    c.my_dict['a'][0] = 1
    >>> vars(c)
    {'a': [1], 'my_dict': {'a': [1]}}