Encapsulation is one of the fundamental aspects of Object Oriented Programming.
Encapsulation serves to protect the data stored within your objects and provides control and conventions for how you should handle the flow of data in and out of classes.
Python does not have the private keyword, unlike some other object oriented languages, but encapsulation can be done. Instead, it relies on the convention: a class variable that should not directly be accessed should be prefixed with an underscore.
What Is Encapsulation
Encapsulation is the process of using private members within classes to prevent unintentional or potentially malicious modification of data.
This post presumes that reader has prior knowledge of how Public , Protected & Private members work, if not then please read about it by clicking here.
Through encapsulation variables and certain methods can only be interacted with through the interfaces designated by the class itself.
Let’s understand it using an example below-
>>> class Rectangle: def __init__(self, height, width): self.__height = height self.__width = width >>> rect= Rectangle(1200,14) >>> rect.__height AttributeError: 'Rectangle' object has no attribute '__height'
We see that we receive an error message stating that the attribute doesn’t exist. This is because that variable is private.
Setters and Getters
The interfaces that are used for interacting with encapsulated variables are generally referred to as setter and getter methods because they’re used to set and retrieve the values of variables. Because methods exist within a class or object, They are able to access and modify private variables, while you will not be able to do so from outside the class. When you instantiated your rect object, you essentially used its constructor as an initial setter method. Try writing a set of methods to set and get the value of one of the rect variables.
>>> class Rectangle: def __init__(self, height, width): self.__height = height self.__width = width def set_vars(self, height,width): self.__height = height self.__width = width def get_vars(self): return self.__height ,self.__width def area(self): return self.__height * self.__width
Now try running the area method.
>>> rect=Rectangle(23,24) >>> print(rect.area()) 552
Everything works fine. That’s because the variable is being accessed by a method within the class, not externally.
Now let’s access using setters and getters.
>>> rect.get_vars() (23, 24) >>> rect.set_vars(143,144) (123, 144)
Voila , Everything work fine !!0