Encapsulation is a principle of object-oriented programming that promotes the bundling of data and methods within a class. It hides the internal details and provides a public interface for interacting with the object. Access modifiers are used to control the visibility and accessibility of class members (attributes and methods) from outside the class.
Let’s explore encapsulation and access modifiers in Python:
# Encapsulation and access modifiers
class Car:
def __init__(self, brand, model, year):
self._brand = brand # Protected attribute
self.__model = model # Private attribute
self.year = year # Public attribute
def __display_private(self):
print("Private method.")
def display_public(self):
print("Public method.")
self.__display_private()
# Creating object
car = Car("Toyota", "Camry", 2020)
# Accessing attributes (protected and public)
print("Brand:", car._brand)
print("Year:", car.year)
# Calling methods (public)
car.display_public()
Explanation:
- We define a class
Car
with attributes_brand
(protected),__model
(private), andyear
(public). - The
_brand
attribute is considered protected, indicating that it should not be accessed directly from outside the class. However, it can still be accessed, although it is conventionally treated as private. - The
__model
attribute is marked as private, meaning it should not be accessed or modified from outside the class. - We define a private method
__display_private()
that is meant to be used internally within the class. - We define a public method
display_public()
that can be accessed from outside the class. It also calls the private method.
Now it’s time for a practical task:
Task 13:
Refactor the Rectangle
class (from a previous lesson) to encapsulate the width
and height
attributes by marking them as private. Create getter and setter methods (get_width()
, get_height()
, set_width()
, set_height()
) to access and modify the attributes. Test the getter and setter methods by creating a Rectangle
object, setting its width and height, and retrieving their values.
Once you’ve completed the task, you can proceed to the next lesson.