Junior — Middle
How can access to private class members be implemented from outside its definition?
sobes.tech AI
Answer from AI
In Python, private class members are indicated by a double underscore at the beginning of the name (e.g., __private_var). This leads to name mangling — the variable's name is prefixed with the class name to make direct access from outside more difficult.
However, access to such members is still possible if you know how Python changes the name. For example:
class MyClass:
def __init__(self):
self.__private_var = 42
obj = MyClass()
# Direct access will cause an error:
# print(obj.__private_var) # AttributeError
# But you can access it like this:
print(obj._MyClass__private_var) # Will output 42
Additionally, you can use class methods (getters/setters) or properties (@property) to control access to private data.
It's important to understand that in Python, privacy is a convention, not strict protection, and direct access to "private" members is possible if necessary.