Junior — Middle
Is it possible to access private variables and methods in Python, and how is it implemented?
sobes.tech AI
Answer from AI
Python does not have true private variables and methods like some other languages. However, a convention using one or two underscores is used to denote private class members:
- A single underscore
_varis just a convention indicating that the variable or method is intended for internal use and should not be accessed outside the class. - A double underscore
__varactivates the name mangling mechanism, which changes the name of the variable within the class to make external access more difficult.
Nevertheless, it is possible to access such "private" variables if you know their mangled 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 via name mangling:
print(obj._MyClass__private_var) # Will output 42
Thus, privacy in Python is more about convention and a mechanism to hinder access rather than strict protection.