Private Variables in Python

Use name-mangling with double underscores to indicate private attributes.

IntermediateObject-Oriented ProgramsExample 17 of 25
private-variables.py
1# Program to demonstrate private variables (name mangling)
2
3class Secret:
4 def __init__(self, data):
5 self.__data = data
6
7 def reveal(self):
8 print("Secret is:", self.__data)
9
10s = Secret("hidden")
11s.reveal()
12
13# Direct access would fail: s.__data

Output

Secret is: hidden

What's going on

Attributes starting with __ are name-mangled to _ClassName__attr, discouraging external access.

After this program

If the idea is still fuzzy, read Day 11: Classes and Objects in the Python course. For a short check, try the Python quiz (300 questions). Stay with all 25 object-oriented programs, or see every topic on Python exercises.