How to declare private variable in Python | Example code

Python does not have any private variables as Java does. Access member variable is available in Python. However, don’t need private variables in Python, because it’s not bad to expose your classes member variables.

The double underscore “__” does not mean a “private variable”. Use it to define variables that are “class local” and which can not be easily overridden by subclasses. It mangles the variable’s name.

source: stackoverflow.com/

How to declare a private variable in Python example

Simple example code uses two underscores to emulate a private variable.

class C:
    def __init__(self):
        self.__a = "Private variable"

    def get_a(self):
        print(self.__a)


obj_C = C()
obj_C.get_a()

Output:

How to declare private variable in Python

In short: there is no way to have a truly “private” class member in Python.

Do comment if you have any doubts and suggestions on this Python variable tutorial.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.