Introduction to Encapsulation in Python
Introduction to Encapsulation
Welcome back! After diving deep into classes in our last session, we're now shifting our focus to another essential concept in Object-Oriented Programming (OOP): encapsulation.
Encapsulation is a way to bundle the data (variables) and methods (functions) that operate on the data, and to restrict direct access to some of an object's components, which can prevent the accidental modification of data. By keeping the data attributes private and providing public methods to access and modify the attributes, you ensure that the internal state of the object can only be changed in controlled ways.
In Python, attributes can be public (accessible from outside the class) or private (not directly accessible from outside the class). Public attributes are meant to be accessed directly, while private attributes are to be accessed and modified through methods within the class.
Create Private Attributes
Let's start by defining a simple Person class with private attributes.
To apply encapsulation, we need to make the attributes private by prefixing them with double underscores (__):
Now, __name and __age are private attributes. It is important to note, however, that Python doesn't have truly private attributes. Prefixing an attribute with double underscores (__) is a convention to indicate it should not be accessed directly outside the class. This name mangling feature helps prevent accidental access and modification but can still be bypassed if necessary.
Getter Methods
Next, let's add methods to access these private attributes. These methods are known as getter methods: methods which provide controlled and consistent access to private attributes, facilitate debugging by centralizing access logic. They allow for calculations or transformations before returning values and offer abstraction that enables changes to the underlying data structure without impacting external code. Here is an example of these methods:
Setter Methods
