Encapsulation
Last updated
Last updated
Encapsulation is related to a concept of information hiding. By following the practices of encapsulation, we can restrict the access to the classes/objects’ certain attributes and methods.
Encapsulation's main purpose is to bundle data/attribute with the methods that operate on that data. Encapsulation is used to hide the values or state of a structured data object inside a class, preventing unauthorized parties’ direct access to them.
To encapsulate attributes or methods in Python, we use the __
prefix. (Double Underscoring)
If you examine the Car
class, we have 1 new attribute and 3 new methods.
Our new attribute: mileage
is encapsulated. Therefore, we cannot access the value out side of the class definition.
Since mileage
is encapsulated, it is often a common practice to write a getter
method to be able to grab hidden data. The method is designed to grab encapsulated data in a controlled and safe way. (Example: get_mileage()
)
When you want to design methods that you don't want objects to have access to, but you want your class definition to have access, you can also encapsulate methods with double underscoring as well. (Example: __reset_mileage()
)
getters
and setters
?PLEASE DEFINE GETTERS BEFORE SETTERS
Getters retrieve value of a private attribute.
In Python, we use a decorator (use of @ symbol)
The following code snippet above is a getter for the attribute.
An object can now reference an attribute called name
by invoking .name
without the use of a method call with brackets like: .name()
.
Creating a getter allows us to access variables that are encapsulated; moreover, you can create attributes that are read-only.
Setters set or update a private attribute.
Setters are important because we get to control how an encapsulated can be changed.
The name
attribute can still be updated by using the =
operator; however, it will execute the setter we created above.