Encapsulation in Python
Encapsulation is one of the most fundamental concepts in object-oriented programming (OOP). This is the concept of wrapping data and methods that work with data in one unit. This prevents data modification accidentally by limiting access to variables and methods. An object’s method can change a variable’s value to prevent accidental changes. These variables are called private variables.
Encapsulation is demonstrated by a class which encapsulates all data, such as member functions, variables.
Encapsulation is nothing but hinding changes.
There are two things:
- Method Overloading
- Method Overriding
1. Method Overloading :
In Method overloading the same method names but different signiture/ parameter. If we define methods with same name with different signature then it will pickup last method. python don’t support the method overloading.
In Above example we create a one class i.e Test and it having same name methods add. when we will create a object and call the method add that time it will pickup the last method.
Get Vrushali Walekar’s stories in your inbox
Join Medium for free to get updates from this writer.
Let’s see in above example it will pickup the last method and gives the above output.
2. Method Overriding:
In method overriding we have same method name in parent and child class. We can also access the parent method so we need to use super keyword to access parent class method.
- Use the super() Function:
Python also has a super() function that will make the child class inherit all the methods and properties from its parent. By using the super() function, you do not have to use the name of the parent element, it will automatically inherit the methods and properties from its parent.
It is a built-in function that returns the objects that represent the parent class. It allows to access the parent class’s methods and attributes in the child class.
Here, class B is derived class which inherited from parent class A. In Class B we use super() method. when we create a object for class B and called the child class printdata then super().printdata allows us to access the parent class’s methods and attributes in the child class.
Example of Method Overriding:
Here, we have created two classes that simulate parent and child functionality.
Then also created two methods itself each that represented the same name such as display().
Next, I created an object for the child class that extended from the parent class. When execute the print statement under the display() method, it will override the class parent statement and display that given below.
I hope, you understood very well about the Encapsulation.we will see the rest of OOPs concepts in the next article.
Thanks for Reading!
#vevcodelab







