I'm working with a Python class that includes private variables. Here's what my code looks like:
```python
class Exam:
def __init__(self, name, roll, branch):
self.__name = name
self.__roll = roll
self.__branch = branch
obj = Exam("Tiger", 1706256, "CSE")
print(obj._Exam__name)
```
When I run this, I can access the private variable `__name` using `obj._Exam__name`, which outputs 'Tiger'. Can someone explain how this works? What's the logic behind accessing private variables like this? I know that to access a private variable or method from outside the class, you can use the `_ClassName` prefix, but I want to understand it better.
3 Answers
In the Python philosophy, truly 'private' variables are considered useless by some. The double underscore name mangling is a way to avoid accidental access, but it's not foolproof. If you just want to signal to other developers that a variable shouldn't be accessed directly, using a single underscore is sufficient.
Private variables in Python are a bit tricky because they actually get name-mangled. When you define a variable with a double underscore, Python changes its name to include the class name, hence you access it with `_Exam__name`. However, a better practice is to use a single underscore as it indicates that the variable is protected, not private. This helps avoid confusion, and it's generally the accepted way to handle variable privacy in Python.
Simply using a single underscore in front of a variable makes it protected, and you can still access it using `obj._method`. It's a simpler way to indicate a variable is not meant to be accessed directly, while still allowing access if absolutely necessary.
Totally get that! Could you share your experiences or tips on when you've needed to access private or protected data?

Right, single underscores are more common. I rarely use private variables myself, but I find understanding these concepts useful for mastering the language!