Sobes.tech
Junior — Middle

How can you call a private method from outside the class in a programming language?

sobes.tech AI

Answer from AI

In Python, private methods are indicated by one or two underscores at the beginning of the name (for example, _method or __method). However, this is only a convention, and access to such methods is possible from outside the class.

For methods with double underscores, Python applies name mangling — the method's name is changed to prevent accidental access. But you can still access the method using the mangled name.

Example:

class MyClass:
    def __private_method(self):
        print("Private method called")

obj = MyClass()

# Calling directly will cause an error:
# obj.__private_method()  # AttributeError

# But you can call it like this:
obj._MyClass__private_method()  # Private method called

For methods with a single underscore (for example, _method), there are no access restrictions; it's just a convention.

Thus, private methods can be called from outside using name mangling or directly if it is a method with a single underscore.