Introduction to Encapsulation
Encapsulation is an object-oriented programming concept where an object’s data and behavior are bundled together, and access to the object’s data is restricted from outside the object. This can be achieved in Python using private and protected attributes and methods.
Private and Protected Attributes and Methods
- Protected attributes and methods: These are indicated by a single underscore before the name (e.g.,
'_attribute'). This is a convention that tells other developers that these attributes and methods should not be accessed directly, but it’s not enforced by the Python interpreter. - Private attributes and methods: These are indicated by double underscores before the name (e.g.,
'__attribute'). Python enforces some degree of privacy by name mangling, which makes it more difficult to accidentally access or modify these attributes and methods from outside the class.
Example:
class MyClass:
def __init__(self):
self.public_attr = "I'm public!"
self._private_attr = "I'm private!"
self.__protected_attr = "I'm protected!"
def public_method(self):
return "I'm a public method!"
def _private_method(self):
return "I'm a private method!"
def __protected_method(self):
return "I'm a protected method!"
Properties and Setters
Python provides a way to control access to an object’s attributes using properties and setters. The decorator allows you to create read-only attributes, while the 'property' decorator allows you to define custom behavior for modifying an attribute’s value.'setter'
Example:
class Circle:
def __init__(self, radius):
self.__radius = radius
@property
def radius(self):
return self.__radius
@radius.setter
def radius(self, value):
if value < 0:
raise ValueError("Radius cannot be negative")
self.__radius = value
Abstraction and Abstract Classes
Abstraction is an OOP concept where only the essential features of an object are exposed, while the details are hidden. Abstract classes are classes that cannot be instantiated and are meant to be subclassed by other classes. Abstract classes can have abstract methods, which are methods with no implementation that must be overridden by subclasses.
To create an abstract class in Python, you can use the 'abc' module and the '@abstractmethod' decorator:
Example:
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
@abstractmethod
def perimeter(self):
pass
Hands-on Exercises
- Create a Python script that defines a
'BankAccount'class with private attributes for the account balance and methods for depositing, withdrawing, and checking the balance. - Create a Python script that defines an abstract
'Shape'class with abstract methods for calculating the area and perimeter. Implement subclasses for'Circle','Square', and'Triangle'that provide the required method implementations. - Create an abstract
'Animal'class with abstract methods for making sounds and eating. Implement subclasses for different animals, such as'Dog','Cat', and'Bird'.
Real-World Example
Encapsulation and abstraction are essential concepts in software design, especially when building large-scale systems. They help ensure that different components of a system can work together without interfering with each other’s internal details, making it easier to maintain and update the code.
Additional Resources
- Python documentation: https://docs.python.org/3/library/abc.html
- Real Python: https://realpython.com/inheritance-composition-python/
- W3Schools Python tutorial: https://www.w3schools.com/python/python_classes.asp
Review Questions
- What is encapsulation in Python, and how can it be used to hide internal implementation details of a class?
- Explain the difference between private and protected attributes and methods in Python.
- What are properties and setters, and how can they be used to control access to attributes?
- What are abstract classes and methods, and how can they be used to define a blueprint for subclasses?
Summary and Next Steps
In this lesson, you have learned about:
- Encapsulation and access control in Python
- Properties and setters for controlling access to attributes
- Abstraction and abstract classes
In the next lesson, you will learn about file handling in Python, including reading and writing files, working with different file formats, and exception handling.
Remember to review the material periodically and practice your skills to reinforce your learning. Good luck on your journey to becoming a Python developer



