How to Create Private Methods in Python Classes

In this tutorial, we will learn how to create private methods in Python classes, a valuable concept that enhances security and prevents unauthorized access to class methods.

Unlike other object-oriented programming languages, Python does not contain a built-in private keyword. Instead, we need a unique workaround to create private methods in Python.

Step 1: Understanding the Concept of Private Methods

In Python, a method can be made private by prefixing the method name with a double underscore ‘__’. A private method cannot be called on the object outside the class. It can only be accessed within a class.

Step 2: Defining the class and Private Method

The following is the Python syntax for creating private methods in a class:

Step 3: Accessing a Private Method

To access a private method, we have to define another method that calls this private method internally, like so:

You can call this method with the object of ClassName because it’s public.

Step 4: Handle Errors

Remember, private means it cannot be accessed directly outside the class. If you try to do so, you will get an error:

This will output the error:

AttributeError: 'ClassName' object has no attribute '__private_method'

Step 5: Correct Way to Call Private Method

The correct way to call a private method is to call it through a public method:

Full Python Code:

Here is the full Python code as mentioned in the tutorial:

This is a private method

Conclusion

In Python, creating private methods can enhance the security of your code, but remember: you cannot call these methods directly. Use a companion public method instead.

By following the steps mentioned in this tutorial, you can effectively create and use private methods in Python classes.