8.1. Encapsulation About
8.1.1. Direct Attribute Access
Setting attibutes directly from outside of the class is not a good idea.
It can lead to unexpected behavior and bugs.
Example:
User.do_something()acts differently based on the value ofUser.authenticatedattributeExample:
User.authenticatedattribute can be set toTrueorFalsefrom outside of the class
>>> class User:
... def __init__(self, name):
... self.name = name
... self.authenticated = False
...
... def do_something(self):
... if not self.authenticated:
... print('Error')
... else:
... print('Done')
...
>>>
>>>
>>> myuser = User('Alice')
>>>
>>> myuser.do_something()
Error
>>>
>>> myuser.authenticated = True
>>>
>>> myuser.do_something()
Done
>>>
>>> myuser.authenticated = False
8.1.2. Accessor Methods
Accessors are methods that allow you to access and modify the attributes of a class.
They are also known as getters and setters.
They provide a way to control access to the attributes of a class.
But, this is not a good idea either.
>>> class User:
... def __init__(self, name):
... self.name = name
... self.authenticated = False
...
... def do_something(self):
... if not self.authenticated:
... print('Error')
... else:
... print('Done')
...
... def set_authenticated(self, value):
... self.authenticated = value
...
... def get_authenticated(self):
... return self.authenticated
...
>>>
>>>
>>> myuser = User('Alice')
>>>
>>> myuser.do_something()
Error
>>>
>>> myuser.set_authenticated(True)
>>>
>>> myuser.do_something()
Done
>>>
>>> myuser.set_authenticated(False)
8.1.3. Encapsulation
Encapsulation is the practice of hiding the internal state of an object and requiring all interaction to be performed through an object's methods.
It allows for changing the internal implementation of an object without affecting the rest of the code.
It is a fundamental principle of object-oriented programming.
>>> class User:
... def __init__(self, name):
... self.name = name
... self.authenticated = False
...
... def do_something(self):
... if not self.authenticated:
... print('Error')
... else:
... print('Done')
...
... def login(self):
... self.authenticated = True
...
... def logout(self):
... self.authenticated = False
>>>
>>>
>>> myuser = User('Alice')
>>>
>>> myuser.do_something()
Error
>>>
>>> myuser.login()
>>>
>>> myuser.do_something()
Done
>>>
>>> myuser.logout()
8.1.4. Case Study
Accessor methods: setters, getters and deleters are a common practice in Java and C++:
>>> class Point:
... _x: int
... _y: int
... _z: int
...
... def set_x(self, value):
... self._x = value
...
... def get_x(self):
... return self._x
...
... def del_x(self):
... self._x = None
...
... def set_y(self, value):
... self._y = value
...
... def get_y(self):
... return self._y
...
... def del_y(self):
... self._y = None
...
... def set_z(self, value):
... self._z = value
...
... def get_z(self):
... return self._z
...
... def del_z(self):
... self._z = None
>>>
>>>
>>> pt = Point()
>>>
>>> pt.set_x(1)
>>> pt.set_y(2)
>>> pt.set_z(3)
>>>
>>> position = pt.get_x(), pt.get_y(), pt.get_z()
>>> print(position)
(1, 2, 3)
Let's introduce feature, that z-axis cannot be negative (value below 0). Although we cannot change previously defined API (methods). If we change API it will break our end-users code and we don't want that. However we can change our class code without any problem.
Not a big of a deal. We already have placeholders to inject such validation. What was previously considered as an overhead, eventually gave us future proof. Very good!
Java way:
>>> class Point:
... _x: int
... _y: int
... _z: int
...
... def set_x(self, value):
... self._x = value
...
... def get_x(self):
... return self._x
...
... def del_x(self):
... self._x = None
...
... def set_y(self, value):
... self._y = value
...
... def get_y(self):
... return self._y
...
... def del_y(self):
... self._y = None
...
... def set_z(self, value):
... if value < 0:
... raise ValueError('Value must be greater than 0')
... self._z = value
...
... def get_z(self):
... return self._z
...
... def del_z(self):
... self._z = None
>>>
>>>
>>> pt = Point()
>>>
>>> pt.set_x(1)
>>> pt.set_y(2)
>>> pt.set_z(3)
>>>
>>> position = pt.get_x(), pt.get_y(), pt.get_z()
>>> print(position)
(1, 2, 3)
>>>
>>> pt.set_z(-1)
Traceback (most recent call last):
ValueError: Value must be greater than 0
Encapsulation:
Defining setter, getter and deleter methods for each property is not a valid way to do an encapsulation. In Java there is project Lombok which can generate setters and getters for your fields automatically and you can overwrite only those which need to be overwritten. But, this not a sustainable solution and it requires a 3rd-party library installation as dependency.
Real encapsulation is about something else. It is about creating an abstraction over your implementation in order to be allowed to change it in future.
>>> class Point:
... def __init__(self, x, y, z):
... self.x = x
... self.y = y
... self.z = z
...
... def set_coordinates(self, x, y, z):
... self.x = x
... self.y = y
... self.z = z
...
... def get_coordinates(self):
... return self.x, self.y, self.z
...
... def del_coordinates(self):
... self.x = None
... self.y = None
... self.z = None
>>>
>>>
>>> pt = Point(1, 2, 3)
>>> pt.set_coordinates(4, 5, 6)
>>> pt.get_coordinates()
(4, 5, 6)
Now, I can change from Cartesian coordinate system to spherical coordinates without a big of a hassle and without breaking public API:
>>> class Point:
... def __init__(self, r, theta, phi):
... self.r = r
... self.theta = theta
... self.phi = phi
...
... def set_coordinates(self, r, theta, phi):
... self.r = r
... self.theta = theta
... self.phi = phi
...
... def get_coordinates(self):
... return self.r, self.theta, self.phi
...
... def del_coordinates(self):
... self.r = None
... self.theta = None
... self.phi = None
>>>
>>>
>>> pt = Point(1, 2, 3)
>>> pt.set_coordinates(4, 5, 6)
>>> pt.get_coordinates()
(4, 5, 6)