What’s New ?

The Top 10 favtutor Features You Might Have Overlooked

Read More

Private Methods in Python

  • Oct 18, 2021
  • 7 Minutes Read
  • Why Trust Us
    We uphold a strict editorial policy that emphasizes factual accuracy, relevance, and impartiality. Our content is crafted by top technical writers with deep knowledge in the fields of computer science and data science, ensuring each piece is meticulously reviewed by a team of seasoned editors to guarantee compliance with the highest standards in educational content creation and publishing.
  • By Shivali Bhadaniya
Private Methods in Python

 

Encapsulation is one of the important concepts in object-oriented programming. It refers to the idea of wrapping the data and the methods that work within one unit or class. Therefore, it helps to put restrictions on accessing the methods and variables directly to prevent the modification of the data. There are many access modifiers that help us with such restrictions and avoid other classes to use the methods and variables accordingly. In this article, let us study one of these access modifiers named Private in detail with all the necessary operations and examples. Let's get started!

What are Private Methods in Python? 

A private method is an access modifier used in a class that can only be called from inside the class where it is defined. It means that you cannot access or call the methods defined under private class from outside.

Consider a real-life example as a car engine. The car engine is made up of various parts like valves, sparks, pistons, etc. No user can make use of these parts by themselves. The same situation is with a private method which hides the inner functionality of the class from the outside world.

Remember that even the base class cannot access the methods of private class. In python programming, there are no private methods that cannot be accessed except inside the class. To define the private method, you have to prefix the member name with a double underscore(__).

The __init__() Method

The fundamental private method in Python is the __init__() method which is used as a class constructor. This method is called when you initiate the class object depending on the method’s argument.

Check the example below where we declare a class “Fruit” with two attributed and an __init__() method:

class Fruit:

    name = ''
    quantity = 0

    def __init__(self, n, a):

        self.name = n
        self.quantity = a

 

Now to access the __init__() method outside the class, we would need to access it from the object of its class after instantiating it.

For instance, another file in the same directory create an instance of class “fruit” and call the constructor using the class name.

sys.path.append(".")

from fruitClass import Fruit

fruit = Fruit("Apple", 10)

print(fruit.name, fruit.quantity)

 

Remember that to import the classes from another file into the current file you have to use the “sys.path.append()” method with the string path directory of the class.

As the in-built method is been discussed, let us move to understand the actual implementation of your own private methods.

Defining Private Methods and Attributes 

To define a private attribute or method in python, you have to just prefix the name with a single underscore(_).

For example, here we have a class named "Class" and the __init__ method is defined with one attribute “var” with its value equals 2. Later the get_var method returns the value of the "var" attribute by defining a function as shown below:

class Class:
  def __init__(self):
    self.var = 2

  def get_var(self):
    return self.var

 

Now, we will rewrite the above example to make “var” and “get_var” as private attributed.

class Class:
  def __init__(self):
    self._var = 2
  def _get_var(self):
    return self._var

 

Pretty simple, isn’t it?

When we try to access this method the output of the program will be 2. You must be wondering that how is this possible because we cannot access the private attribute and methods, right?

In python, private access to private methods and attributes is not enforced. Therefore, when attributes start with a single underscore, that is just a convention and not an enforced decision.

Python does not support encapsulation but that doesn’t mean you must access attributed and methods that are prefixed with an underscore. Moreover, if you are designing your own library or class, you are recommended to use the variable names with a single underscore as a prefix to specify that attributes and methods shouldn’t be accessed.

This was all about the names with a single underscore as a prefix, but what about two underscores or no trailing underscores. Let's discuss about that now.

Name Mangling

Let us define the attribute “var” and “get_var” from the above example but using double underscore.

For Example:

class Class:
  def __init__(self):
    self.__var = 2

  def __get_var(self):
    return self.__var

 

When you run the above program, an error will be generated which suggests "no such attribute “__var” is available" even though we have defined the value of the “var” attribute.

This error can be solved by replacing the class name before the name of the attribute. For example, attribute “var” becomes “_Class__var” for the above class. Similarly, “get_var” becomes “_Class__get_var”.

This change in the behaviour of the attribute is called the name mangling. Therefore, python provides a special concept that can be used to call the private method from outside the class known as the name mangling.

Remember that accessing the variables of private class from outside is harder using name mangling, but still, it is accessible through “_Class__var”.

Many developers and programmers make mistakes using the name mangling technique to denote the private attributes and methods of the class. But it should be taken care of that denoting private methods and attributes is not the primary function of name mangling.

Conclusion

Encapsulation is the most fundamental concept of python programming which provides multiple access modifiers to protect our class and methods from the outside world. The private method is one of those access modifiers which is highly used by every developer to protect their codes and data from others. It is always recommended to learn and understand private methods when you are keen to develop your own class or libraries in python programming.

FavTutor - 24x7 Live Coding Help from Expert Tutors!

About The Author
Shivali Bhadaniya
I'm Shivali Bhadaniya, a computer engineer student and technical content writer, very enthusiastic to learn and explore new technologies and looking towards great opportunities. It is amazing for me to share my knowledge through my content to help curious minds.