Junior — Middle
How to implement a class method so that it is not accessible from outside for modification or invocation?
sobes.tech AI
Answer from AI
In Python, there is no strict privacy for methods, but conventions can be used to restrict access:
- Single underscore (_method): indicates that the method is intended for internal use, but does not prevent external calls.
- Double underscore (__method): leads to name mangling — the method's name is changed to make external access more difficult.
Example:
class MyClass:
def __private_method(self):
print("This is a private method")
def public_method(self):
self.__private_method()
obj = MyClass()
obj.public_method() # Works
# obj.__private_method() # AttributeError
# But you can call it like this:
obj._MyClass__private_method() # Works, but not recommended
Thus, to implement a method that should not be accessible from outside, double underscore is used in the method's name.