Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python mutable class variable vs immutable class variable

Running the sample code below:

class S:
    i = 0
    a = []
    def __init__(self):
        self.i += 1
        self.a.append(1)

s1 = S()
print((s1.i, s1.a))

s2 = S()
print((s2.i, s2.a))

The output will be:

(1, [1])
(1, [1, 1])

My question is why the int S.i reset to 0 for s2 but the list S.a does not reset to empty? I think it has something to do with the immutable int vs mutable list but could someone help to express more details what happened to the two class variables during the two init calls? Thanks!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

self.i += 1

is equivalent to

self.i = self.i + 1

When the instance variable does not exist, the value is looked up on the class, so in this scenario, it is equivalent to

self.i = S.i + 1

After you define self.i, then any further value lookup is on the instance variable, not on the class variable. So after this line, you have S.i = 0 and s1.i = 1. Since S.i is not modified, s2.i also becomes 1.

On the other hand,

self.a.append(1)

does not create a new instance variable, but appends an element to the existing class variable.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading