Junior — Middle
How can access to internal methods and variables of a class be restricted in Python?
sobes.tech AI
Answer from AI
Python does not have a strict access restriction system like some other languages (for example, private in Java or C++). However, there are conventions and mechanisms that help indicate internal methods and variables:
- A single underscore
_varindicates that the variable or method is intended for internal use (protected by convention). - A double underscore
__varactivates name mangling, where the variable name is changed to_ClassName__var, making external access more difficult.
Example:
class MyClass:
def __init__(self):
self.public_var = 1
self._protected_var = 2
self.__private_var = 3
def __private_method(self):
print("This is a private method")
obj = MyClass()
print(obj.public_var) # 1
print(obj._protected_var) # 2 (possible, but not recommended)
# print(obj.__private_var) # AttributeError
print(obj._MyClass__private_var) # 3 (access via name mangling)
# Calling a private method
# obj.__private_method() # Error
obj._MyClass__private_method() # Works
Thus, double underscores serve as a way to limit access, but it is more of a convention and a bypass mechanism rather than strict protection.