Encapsulation
In programming, we define encapsulation as the bundling of data (attributes) and methods (functions) that operate on the data into a single unit, called a class
. It’s a way to protect the data from being modified by external code. It’s a fundamental concept in object-oriented programming.
Python3 provides a way to define private attributes and methods. We use the _
and __
to indicate that an attribute or a method is private. This means that they can only be accessed within the class. The difference between _
and __
is that the former is a convention, while the latter is a language feature and enables name mangling
, aka you cannot (almost) access it from outside the class.
How to define encapsulation
class Beam:
def __init__(self, length=2, width=0.2, height=0.5):
self._length = length # we use _ to indicate that this is a private attribute
self._width = width
self._height = height
self.__volume = None # we use __ to indicate that this is a private attribute
def __calculate_volume(self):
self.__volume = self._length * self._width * self._height
def get_volume(self):
self.__calculate_volume()
return self.__volume
How to use encapsulation
beam = Beam()
print(beam.get_volume()) # 0.2
# not reccomended, but still possible
beam._length = 3
print(beam.get_volume()) # 0.3
# not recommended, and not possible
beam.__volume = 10 # AttributeError: 'Beam' object has no attribute '__volume'
⚠️⚠️⚠️Note that we can still access the private attributes and methods (_), but it’s not recommended. We should use the public methods to access the private attributes and methods.⚠️⚠️⚠️