- Private Methods in Python
- What are Private Methods in Python?
- Differences Between Private and Public Methods
- Example 1: Creating Private Methods in Python
- Example 2: Accessing Private Methods in Python
- Example 3: Call Private Methods Outside the Class (Name mangling)
- Conclusion
- Private Methods in Python
- P rivate functions in Python
- Private Methods in Python
- What are Private Methods in Python?
- The __init__() Method
- Defining Private Methods and Attributes
- Name Mangling
- Conclusion
Private Methods in Python
Private methods are used to help users serve with “Encapsulation.” This means that methods are accessible only inside the same class and not from outside it. In Python, private methods cannot be accessed/called outside the class.
This post provides an in-depth guide on private methods using numerous examples and following the below contents:
What are Private Methods in Python?
In Python, private methods can only be called inside the same class where they are initialized. They cannot be called outside the class, even by subclasses. Private methods are denoted by double underscores (__), as shown below:
class class_name: def __private_method(self): # do something
Python’s private methods can be used for the following purposes:
- A class’s internal workings are hidden from the outside world by using private methods.
- They encapsulate the class’s behavior, preventing other classes from directly accessing or modifying the class’s state.
Differences Between Private and Public Methods
The difference between private and public methods are shown below:
Private Methods | Public Methods |
---|---|
private methods can only be accessed/called inside the class. | Public methods can be called inside the class. |
private methods are used to implement its internal behavior. | Public methods are used to define the external interface of a class. |
private methods can only be called by other methods within the same class. | Public methods can be called by any object. |
Example 1: Creating Private Methods in Python
To create a private method, the member name must be prefixed with the double underscore “__.” Here is an example of how to create a private method in Python:
class school: def __private_method(self): print("This is a private method") def public_method(self): print("This is a public method") self.__private_method() obj = school() obj.public_method()
- The class defined two methods named as “ __private_method” and “public_method”.
- The private method named “__private_method()” is defined using the double underscore at the start.
- The private is accessed inside the public method using the expression “self.__private_method()”.
- The class object named “obj” is used to call the public method.
The private and public methods are created and accessed using the class object.
Example 2: Accessing Private Methods in Python
Private methods cannot be accessed directly outside the class. However, they can be accessed indirectly using other methods within the class. For example, a public method within the same class can call a private method using the below code example:
class Students: def free(self): print("Public method") def __free(self): print("Private method") def boys(self): self.free() self.__free() my_obj = Students() my_obj.boys()
- The class “Students” is created using the keyword class.
- The public method, named “free,” and the private method, by prefixing with a double underscore, are defined.
- The third method, named “boys,” is defined.
- Inside the third method, the public and private method is accessed using the self parameter.
- The class object is used to access the third method, automatically accessing the private and public methods.
The private method has been successfully accessed.
Example 3: Call Private Methods Outside the Class (Name mangling)
The below example is used to call private methods using the Name mangling techniques. The private method is called from outside the class with the help of this technique.
The private method is created using the double underscore, just as shown below:
We need to replace the above with the given below syntax:
In the above case, the “_classname__method” replaces “__method,” where the class name is the current class name.
Now. let’s understand it via the following examples:
class School: def method(self): print("This is a Public method") def __method(self): print("This is a Private method") obj = School() obj._School__method()
- The class name “School” is created at the start.
- The name mangling method, such as “obj._School__method(),” is used to access private methods outside the class.
The private method has been accessed successfully.
Conclusion
A private method in Python can only be accessed/called within the same class in which it is defined. Private methods are denoted by double underscores (__). Accessing private methods directly from outside of a class is impossible. Alternatively, they can be accessed indirectly through other class methods. The class’s private methods can also be accessed through other methods, such as name mangling. This tutorial provided an in-depth overview of Python’s private methods.
Private Methods in Python
Encapsulation is one of the fundamental concepts in object-oriented programming (OOP) in Python. It describes the idea of wrapping data and the methods that work on data within one unit. This puts restrictions on accessing variables and methods directly and can prevent the accidental modification of data. A class is an example of encapsulation as it encapsulates all the data that is member functions, variables, etc. Now, there can be some scenarios in which we need to put restrictions on some methods of the class so that they can neither be accessed outside the class nor by any subclasses. To implement this private methods come into play.
P rivate functions in Python
Consider a real-life example, a car engine, which is made up of many parts like spark plugs, valves, pistons, etc. No user uses these parts directly, rather they just know how to use the parts which use them. This is what private methods are used for. It is used to hide the inner functionality of any class from the outside world. Private methods are those methods that should neither be accessed outside the class nor by any base class. In Python, there is no existence of Private methods that cannot be accessed except inside a class. However, to define a private method prefix the member name with the double underscore “__”. Note: The __init__ method is a constructor and runs as soon as an object of a class is instantiated.
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
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.