How to Create a Private Method in Python?

Estimated read time 2 min read

In Python, you can create a private method by prefixing the method name with two underscores (__). This makes the method name “name-mangled”, meaning it is rewritten to include the class name, which makes it more difficult to access the method from outside the class. Here’s an example code snippet:

class MyClass:
    def __private_method(self):
        print("This is a private method")
    def public_method(self):
        print("This is a public method")

# Example usage:
obj = MyClass()
obj.public_method()   # Output: This is a public method \n This is a private method
obj.__private_method()   # Throws an AttributeError

In this example, we define a MyClass class with a private method __private_method(). We also define a public method public_method() that calls the private method using the self.__private_method() syntax.

We test the class by creating an object obj of type MyClass, and calling the public method public_method(), which successfully calls the private method and prints its output. We also try to call the private method directly using the obj.__private_method() syntax, which throws an AttributeError because the method name is “name-mangled”.

You can modify this code to include more private methods or to use different naming conventions for private methods, such as a single underscore prefix or a suffix. Note that private methods can still be accessed from outside the class using the name-mangled method name, but this is not recommended as it can break encapsulation and lead to unexpected behavior.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply