Sobes.tech
Junior — Middle

How are private methods declared and used inside classes in Python?

sobes.tech AI

Answer from AI

In Python, private methods within classes are declared using a double underscore at the beginning of the method name, for example, __my_private_method. This triggers name mangling — the method's name is changed by the interpreter 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 and calls the private method

# obj.__private_method()  # Error: AttributeError

# But you can access it like this (not recommended):
obj._MyClass__private_method()

It's important to understand that Python does not have true privacy, and the double underscore is merely a convention and a mechanism to prevent accidental access. To denote methods that are not intended for use outside the class, a single underscore _method is also often used — this is just a convention, without name mangling.

How are private methods declared and used inside… - sobes.tech