Skip to content

How to declare private variable in Python | Example code

  • by

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 class 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

A 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.

Please comment if you have any doubts or suggestions on this Python variable tutorial.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

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

Leave a Reply

Discover more from Tutorial

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

Continue reading