Page 412 - Computer_Science_F5
P. 412
Encapsulation in Python considered as protected, implying that
they should not be accessed directly from
Encapsulation is a core concept in outside the class. Attributes and methods
Python Object-Oriented Programming. starting with double underscores (__)
It involves grouping together data and are considered private and cannot be Chapter Six: Object oriented programming with Python
FOR ONLINE READING ONLY
the methods that work on that data into a accessed from outside the class.
single unit called a class. Encapsulation
involves ideas on access modifiers and Getter and setter methods:
'getters and setters' as seen in other Encapsulation often involves the use of
languages. getter and setter methods to access and
modify the attributes of a class. Getter
Access modifiers: methods are used to retrieve attribute
Unlike Java or C++, Python does not values, while setter methods are used to
have built-in access modifiers. Instead, modify them. This approach provides
it relies on conventions to indicate the controlled access to attributes, enabling
accessibility of attributes and methods. data validation and maintaining data
By convention, attributes and methods integrity. The following Program
starting with a single underscore (_) are Example 6.4 demonstrates encapsulation.
Program Example 6.4:
Program codes demonstrating encapsulation
class Person:
def __init__(self, name, age):
self._name = name
self._age = age
def get_name(self):
return self._name
def set_age(self, age):
if age >= 0:
self._age = age
def display_info(self):
print(f”Name: {self._name}, Age: {self._age}”)
# Creating an object of the Person class
person = Person(“John”, 30)
403
Student’s Book Form Five
Computer Science Form 5.indd 403 23/07/2024 12:34

