educative.io

Class variables vs private variable

Class variables are defined outside initializer method are shared with all objects.

(teamName as class variable shared across different objects)

But here I see private variables are defined as class variables outside initializer method .
The variables are not shared across objects.

Behavior of private variables and public variables defined as class variables are different.?
__name , __rollNumber are class variables but not shared across objects?

class Student:
__name = None
__rollNumber = None

def setName(self, name):
    self.__name = name

def getName(self):
    return self.__name

def setRollNumber(self, rollNumber):
    self.__rollNumber = rollNumber

def getRollNumber(self):
    return self.__rollNumber

demo1 = Student()
demo1.setName(“Alex”)
print(“Name:”, demo1.getName())
demo1.setRollNumber(3789)
print(“Roll Number:”, demo1.getRollNumber())
demo2 = Student()
demo2.setName(“kaa”)
print(“Name- after:”, demo1.getName())

Ouput: Shows demo1 reference still hold the value set before.

Name: Alex
Roll Number: 3789
Name- after: Alex

Hi @Anil3,

Basically, that type of class variable is public when it is defined outside the initializer method without the double underscored __ at the start of the variable name. Eg. teamName = 'Liverpool' is a public variable.

The class variable is private when defined outside the initializer method with the double underscored __ at the start of the variable name. Eg. __teamName = 'Liverpool' now it is a private variable.

I hope I have answered your query; please let me know if you still have any confusion.

Thank You :blush: