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

In Python, there is no true private method like there is in some other programming languages. However, a method can be made "private" by prefixing its name with two underscores. This will cause the method to be name-mangled, meaning its name is changed to include the class name as a prefix, thus making it harder to access from outside the class.

To call a private method on an instance of a class in Python, you can use the name-mangled version of the method name. Here is an example:

main.py
class MyClass:
    def __init__(self):
        self.__my_private_method()

    def __my_private_method(self):
        print("This is a private method!")

obj = MyClass()  # Output: This is a private method!
207 chars
9 lines

In this example, __my_private_method() is a private method of MyClass. We call it in the constructor of MyClass by using the name-mangled version of the method name, __my_private_method(). The double underscore prefix causes the method to be name-mangled, which means its name is changed to _MyClass__my_private_method(). We can still call the method using its name-mangled version, however.

It's important to note that name-mangling is just a convention and not true encapsulation. It's still possible to call a private method from outside the class by using its mangled name, although doing so is not recommended.

gistlibby LogSnag