Sobes.tech
Junior — Middle

How can access to protected methods in Python be obtained?

sobes.tech AI

Answer from AI

In Python, protected methods and attributes are indicated by a single underscore at the beginning of the name (e.g., _method). This is a convention, not a strict rule.

To access such methods, it is enough to refer to them directly, for example:

class MyClass:
    def _protected_method(self):
        print("This is a protected method")

obj = MyClass()
obj._protected_method()  # Access is possible

If a method is declared with a double underscore (e.g., __method), name mangling occurs to prevent conflicts in subclasses. Access is then possible through the mangled name:

class MyClass:
    def __private_method(self):
        print("This is a private method")

obj = MyClass()
obj._MyClass__private_method()  # Access via mangled name

Thus, protected methods are accessible directly, while private ones are accessed through the mangled name.