What are public and private variables in Python class?

PythonServer Side ProgrammingProgramming

Public Variables

Python doesn’t restrict us from accessing any variable or calling any member method in a python program.

All python variables and methods are public by default in Python. So when we want to make any variable or method public, we just do nothing. Let us see the example below −


class Mug:
    def __init__(self):
        self.color = None
        self.content = None

    def fill(self, beverage):
        self.content = beverage

    def empty(self):
        self.content = None

brownMug = Mug()
brownMug.color = "brown"
print brownMug.empty()
print brownMug.fill('tea')
print brownMug.color
print brownMug.content

All the variables and the methods in the code are public by default.

When we declare our data member private we mean, that nobody should be able to access it from outside the class. Here Python supports a technique called name mangling. This feature turns every member name prefixed with at least two underscores and suffixed with at most one underscore into _<className><memberName> . So to make our member private, let’s have a look at the example below −


class Cup:
    def __init__(self, color):
         self.__content = None  # private variable
    def fill(self, beverage):
        self.__content = beverage
    def empty(self):
        self.__content = None

Our cup now can be only filled and poured out by using fill() and empty() methods. Note, that if you try accessing __content from outside, you’ll get an error. But you can still stumble upon something like this −

redCup = Cup("red")
redCup._Cup__content = "tea"
Updated on 15-Jun-2020 12:00:23