What is Encapsulation in Python

Encapsulation is one of the fundamental concepts in object-oriented programming.
Encapsulation is the idea of wrapping data and the methods within one unit. This provides restrictions on accessing variables and methods directly and can prevent the unknown modification of data.
To prevent accidental change, an object’s variable can only be changed by an object’s method. Those types of variables are known as private variable.
A class is an example of encapsulation as it encapsulates all the data that is member functions, variables, etc.
In Python, we denote private attributes using underscore as the prefix i.e single _
or double __
.
class Pen: def __init__(self): self.__maxprice = 10 def sell(self): print("Selling Price: {}".format(self.__maxprice)) def setMaxPrice(self, price): self.__maxprice = price p = Pen() p.sell() # change the price p.__maxprice = 100 p.sell() # using setter function p.setMaxPrice(100) p.sell()
Output:
Selling Price: 10 Selling Price: 10 Selling Price: 100
In this example, we defined a Pen class. We used __init__()
method to store the maximum selling price of Pen
. We tried to modify the price. However, we can’t change it because Python treats the __maxprice as private attributes.
As shown, to change the value, we have to use a setter function i.e setMaxPrice()
which takes price as a parameter.