Sobes.tech
Junior — Middle

How to define a class method as private in object-oriented programming?

sobes.tech AI

Answer from AI

Python does not have strict privacy for methods like some other languages (e.g., Java or C++). However, by convention, methods whose names start with a double underscore __ are considered private and undergo name mangling, which makes them harder to call from outside the class.

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()  # Error: AttributeError

# But you can call it like this:
obj._MyClass__private_method()  # Works, but not recommended

Thus, to define a method as private, you should name it with a double underscore at the beginning.