0
0
PythonConceptBeginner · 3 min read

What is Private Variable in Python Class: Simple Explanation

A private variable in a Python class is a variable that is intended to be hidden from outside access by prefixing its name with double underscores, like __var. This triggers name mangling, making it harder (but not impossible) to access from outside the class, helping to protect internal data.
⚙️

How It Works

In Python, private variables are not truly private like in some other languages, but they use a trick called name mangling. When you start a variable name with two underscores (e.g., __secret), Python changes its name internally to include the class name. This makes it harder to access accidentally from outside the class.

Think of it like putting your valuables in a locked box labeled with a secret code only you know. Others can see the box but can't easily open it. However, if someone really wants to, they can figure out the code and open it, so it's more about signaling "keep out" than absolute security.

💻

Example

This example shows a class with a private variable and how it behaves when accessed inside and outside the class.

python
class MyClass:
    def __init__(self):
        self.__private_var = 42  # Private variable

    def get_private_var(self):
        return self.__private_var

obj = MyClass()
print(obj.get_private_var())  # Access via method

# Trying to access directly will cause an error
try:
    print(obj.__private_var)
except AttributeError as e:
    print(e)

# Accessing using name mangling (not recommended)
print(obj._MyClass__private_var)
Output
42 'MyClass' object has no attribute '__private_var' 42
🎯

When to Use

Use private variables when you want to hide internal details of a class from outside code to avoid accidental changes. This helps keep your class's data safe and your code easier to maintain.

For example, if you have a bank account class, you might want to keep the balance private so it can only be changed by specific methods like deposit or withdraw. This prevents other parts of the program from changing the balance directly and causing errors.

Key Points

  • Private variables start with double underscores __ to trigger name mangling.
  • Name mangling changes the variable name internally to include the class name.
  • Private variables are not fully hidden but discourage direct access.
  • Use private variables to protect important data inside classes.

Key Takeaways

Private variables in Python use double underscores to trigger name mangling.
Name mangling makes variables harder to access from outside the class.
Private variables help protect internal data from accidental changes.
You can still access private variables using a special syntax, but it is discouraged.
Use private variables to keep your class data safe and your code clean.