Opens in a new tab
Lesson 4

Encapsulation and Abstraction in Python

Object-Oriented Programming, Python Mastery Program, Stage 2 Python

Written by

Muhammad Atif

Last Updated

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:

Python
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 'property' decorator allows you to create read-only attributes, while the 'setter' decorator allows you to define custom behavior for modifying an attribute’s value.

Example:

Python
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:

Python
from abc import ABC, abstractmethod

class Shape(ABC):
    @abstractmethod
    def area(self):
        pass

    @abstractmethod
    def perimeter(self):
        pass

Hands-on Exercises

  1. 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.
  2. 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.
  3. 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

Review Questions

  1. What is encapsulation in Python, and how can it be used to hide internal implementation details of a class?
  2. Explain the difference between private and protected attributes and methods in Python.
  3. What are properties and setters, and how can they be used to control access to attributes?
  4. 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

Muhammad Atif

Data Analyst & Web Development Professional | Focused on Machine Learning, SQL and Python

Transitioned from a background in finance to IT, I now focus on data science and web development, with specialties in Machine Learning, SQL, and Python. My articles aim to clarify complex IT concepts, informed by a rich history in analytical thinking and strategy.

You Might Also Like

Browse more topics and insights handpicked just for you. Stay updated and informed with our latest articles and news.