Private method in Python

Private method in Python

Have you ever used data structures like pandas dataframe while programming in python? Don’t they make working with complex tabular data a cakewalk? You can just use methods provided in the pandas module and every task is executed. Have you ever thought about how these complex data structures are handled by python? You didn’t! Because you didn’t need that. We don’t need to know and we are not allowed to know what happens behind when we execute those methods. Private methods in Python are often used to implement those operations that a normal user doesn’t need to know the details about. In this article, we will discuss what private methods in python are, how we can use them, and how we can access a private method in python.

What is a private method in Python?

Private methods are such methods that cannot be accessed outside a class definition. In the real world, if something is private to us, other people aren’t supposed to have access to that. Similarly, We are not supposed to access the private methods defined inside a class.

Python doesn’t support private methods. But, we can simulate the implementation of private methods in python. For that, we have to define the name of the private method using two underscore signs as follows.

Here, we have used the def keyword to define the method and the pass keyword has been used to create a method body that does nothing.

Why do we need a private method in Python?

Private methods are used for various purposes by programmers. Let us understand using an example.

For instance, let us create a class named Student to keep the marks of students. Here, we can keep the marks of all subjects using a python dictionary as follows. 

Now, suppose that we create two methods namely strongerSubjects and weakerSubjects. The strongerSubjects method to get the name of those subjects in which the students have scored higher than their average marks and the weakerSubjects method to get the name of those subjects in which they have scored less than their average marks.  We can do it as follows.

Output:

You might observe that we are calculating the average marks in both the methods that are defined above. So, instead of repeating the code, we can define a method to calculate the average marks of the student. Here, the method to calculate the average marks has no significance outside the class definition as we don’t need the average marks of the student. Therefore, to calculate the average marks of the student, we will define a private method. This is so because we don’t need to calculate the average marks of the students. Here, we can define a private method __averageMarks() to calculate the average and reuse the code as follows.

Output:

Creating a separate private method for calculating the average marks gives us the following advantages.

  • We can increase the modularity of the code by creating methods that perform atomic tasks. Also, we can do it without having the need to change how the public methods work. 
  •  We can easily refactor the code of the private methods without changing the implementation of public methods. This makes our code more maintainable.

Can we access a private method in Python?

Private methods can be accessed directly only inside the class definition in Python. If we try to access them outside the class definition, an AttributeError exception will occur as follows.

Output:

But, we can access the private methods in python indirectly. For this, let us first see how names of private methods are stored in python. To obtain the name of methods and fields in a class, we can use the dir() function. 

The dir() function takes a python object as the input parameter and returns the name of all the methods and fields. We can obtain the names of all the methods in the Student class as follows.

Output:

In the output, you can see that the name of the private method __averageMarks has been written as ‘_Student__averageMarks‘. It means the method name has been preceded by _Student i.e. _className. We can access the private method using the full name i.e. _className__methodName() by appending an underscore and class name to the name of the private method as follows.

Output:

Another way with which we can access private methods is to use public methods. Here, we can use the private method but we cannot call the private method directly. For instance, while getting the subjects with marks greater than average marks, we have used the private method in the weakerSubjects() method and strongerSubjects() method but we haven’t accessed that directly. 

Conclusion

In this article, we have discussed what private methods are, and how we can implement them in Python. We have also seen how we can access a private method in python. But, I would suggest you not use a private method outside the class definition. Accessing a private method outside its class definition just violates the idea of why we define them. 

I hope you enjoyed reading this article. Stay tuned for more informative articles. 

Happy Learning.

Related Posts

  • Python check for null
    17 November

    How to check for null in Python

    Table of ContentsHow to check if a variable is NULL in Python?Using the is operator to check if a variable is NULL in Python.Using the if condition to check if a variable is NULL in Python.Using the not equal to operator to check if a variable is NULL in Python. This article demonstrates the different […]

  • Sort dictionary by value in Python
    17 November

    Sort dictionary by value in python

    Table of ContentsHow to sort sort dictionary by value in Python?Using for loop along with the sorted() function.Using the sorted() function to sort dictionary by value in Python.Using operator.itemgetter() function to sort sort dictionary by value in Python.Using lambda function to sort sort dictionary by value in Python.Using the OrderedDict() method to sort sort dictionary […]

  • Get class name in Python
    17 November

    Get class name in Python

    Table of ContentsHow to get the attributes of an object?Get Class name in python using the __class__ attribute Get Class name in python using type() functionConclusion While working with objects in python, several times we need to get their class name. In this article, we will discuss several ways to get the class name of an […]

  • Python print to file
    17 November

    How to Print to File in Python?

    Table of ContentsThe print() function in pythonHow to Print to file in python?Print to file using the file parameter in the print functionPrint to file by redirecting standard outputConclusion We use the print() function in python to print any text to standard output. In this article, we will see how we can use the print() […]

  • Python absolute path
    17 November

    Get Absolute Path in Python

    Table of ContentsWhat is an absolute path to a file? How to get absolute path in PythonUse abspath to get the absolute path to file use pathlib module to get the absolute path to file Conclusion We often use files to store the outputs of our programs in permanent storage. Generally, we work with relative […]

  • Python sort list of lists
    17 November

    Sort List of Lists in Python

    Table of ContentsSort List of Lists Using the sort() Method in PythonUsing the itemgetter() methodUsing Lambda FunctionsSort List of Lists Using the sorted() Function in PythonSort lists of lists on the basis of the length of the inner listsConclusion Several times we use 2-D lists or lists of lists in our programs to represent a […]

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.