call a protected method on an instance of a class in python

In Python, to call a protected method on an instance of a class, you can use the following syntax:

main.py
instance._ClassName__methodName(parameters)
44 chars
2 lines

This syntax uses name mangling to access the protected method. When you define a method with a double underscore prefix in a class, its name gets mangled by the Python interpreter. The name is replaced with _ClassName__methodName, where ClassName is the name of the class where the method is defined.

Here is an example that shows how to call a protected method in Python:

main.py
class MyClass:
    def __init__(self):
        self.__count = 0

    def _increment_count(self):
        self.__count += 1

    def get_count(self):
        return self.__count

obj = MyClass()
obj._MyClass__increment_count()
print(obj.get_count())  # Output: 1
262 chars
14 lines

In this example, we define a class MyClass with a private variable __count and a protected method _increment_count. We create an instance of the class, call the protected method using the name mangling syntax, and then print the value of the private variable. The output will be 1.

gistlibby LogSnag