Zone Of Makos

Menu icon

Abstraction in Python

Abstraction is one of the four main principles of object-oriented programming (OOP), along with encapsulation, inheritance, and polymorphism. In Python, abstraction is the practice of focusing on the essential features of an object and hiding its unnecessary details. This allows you to create a simple and intuitive interface for using the object, without exposing its internal implementation. In this lesson, we'll explore how to use abstraction in Python and how it can help you write more maintainable and reusable code.

Abstract Classes in Python

In Python, abstraction is typically implemented using abstract classes. An abstract class is a class that cannot be instantiated directly, but instead provides a template for other classes to inherit from. Abstract classes define abstract methods, which are methods that do not have an implementation. These methods must be implemented by any class that inherits from the abstract class, otherwise an error will be raised.


from abc import ABC, abstractmethod

class MyAbstractClass(ABC):
    @abstractmethod
    def my_abstract_method(self):
        pass

class MyConcreteClass(MyAbstractClass):
    def my_abstract_method(self):
        print("Implementation of my_abstract_method")

my_object = MyConcreteClass()
my_object.my_abstract_method()

# This will raise an error because MyAbstractClass is an abstract class
# my_abstract_object = MyAbstractClass()

Interfaces in Python

In addition to abstract classes, Python also supports interfaces, which are similar to abstract classes but only define abstract methods. In Python, interfaces are not a separate language feature, but can be emulated using abstract classes that do not have any implemented methods.


from abc import ABC, abstractmethod

class MyInterface(ABC):
    @abstractmethod
    def my_abstract_method(self):
        pass

class MyConcreteClass(MyInterface):
    def my_abstract_method(self):
        print("Implementation of my_abstract_method")

my_object = MyConcreteClass()
my_object.my_abstract_method()

# This will raise an error because MyInterface is an abstract class
# my_interface_object = MyInterface()

Conclusion

Abstraction is an important concept in object-oriented programming that allows you to focus on the essential features of an object and hide its unnecessary details. In Python, abstraction is typically implemented using abstract classes, which define abstract methods that must be implemented by any class that inherits from the abstract class. Python also supports interfaces, which are similar to abstract classes but only define abstract methods. Abstraction helps to make your code more modular and reusable, and it is an essential part of writing clean and maintainable code.

That's come to end of OOPS concepts covered in this course. From next lessons, we'll learn advanced concepts mentioned earlier.