What is Private Variable in Python Class: Simple Explanation
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.
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)
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.