Do class variables in python behaves as instance variable when we instantiate an object?

Viewed 45

Consider the following example:

class Ciao():
    a = 1 
    def whatIsIt(self):
        print(self.a)

i = Ciao()
i.a = 2
i.whatIsIt() #Returns 2

I am creating an instance of the class Ciao, modifying the class variable and then printing it in the last line. To me, the class variable a, after having create the object i, behaves completely as the instance variable in this code snippet.

class Ciao2():
    def __init__(self):
        self.a = None
    def whatIsIt(self):
        print(self.a)
i = Ciao2()
i.a = 2
i.whatIsIt() #Returns 2

Is there any fundamental difference between a class and an instance variable after having instantiate the object?

1 Answers

Yes, there is a fundamental difference. It can be seen when the variables are mutable (e.g. lists), and you work with several instances of the same class. Changes made to a class variable will carry over to all the instances, but changes made to an instance variable will not:

class Ciao():
    a = [1]
    
    def __init__(self):
        self.b = [1]
        
        
i1 = Ciao()
print(i1.a, i1.b)  # [1] [1]
i1.a.append(2)
i1.b.append(2)
print(i1.a, i1.b)  # [1, 2] [1, 2]

i2 = Ciao()
print(i2.a, i2.b)  # [1, 2] [1]
Related