Private Variables

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

IntermediateTopic: Object-Oriented Programs
Back

Python Private Variables Program

This program helps you to learn the fundamental structure and syntax of Python programming.

Try This Code
# Program to demonstrate private variables (name mangling)

class Secret:
    def __init__(self, data):
        self.__data = data

    def reveal(self):
        print("Secret is:", self.__data)


s = Secret("hidden")
s.reveal()

# Direct access would fail: s.__data
Output
Secret is: hidden

Understanding Private Variables

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

Note: To write and run Python programs, you need to set up the local environment on your computer. Refer to the complete article Setting up Python Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your Python programs.

Table of Contents