Language: EN

python-clases-abstractas

How to Use Abstract Classes in Python

An abstract class is a class that cannot be instantiated directly. Its main purpose is to be inherited by other classes that implement the methods defined as abstract in the base class.

In Python, abstract classes are implemented using the abc (Abstract Base Classes) module. This module provides tools to define abstract classes and methods.

from abc import ABC, abstractmethod

Defining an Abstract Class

To define an abstract class, you must inherit from ABC and use the @abstractmethod decorator to mark the methods that must be implemented by subclasses.

For example,

from abc import ABC, abstractmethod

class Animal(ABC):
    @abstractmethod
    def make_sound(self):
        pass

    def sleep(self):
        print("The animal is sleeping.")

In this example,

  • Animal is an abstract class with an abstract method make_sound
  • A concrete method sleep.

Implementing Derived Classes

Classes that inherit from an abstract class must implement all the abstract methods. If a subclass does not implement an abstract method, it also becomes an abstract class and cannot be instantiated.

Let’s see how to implement our abstract class Animal

class Dog(Animal):
    def make_sound(self):
        print("The dog barks.")

class Cat(Animal):
    def make_sound(self):
        print("The cat meows.")

In this example, Dog and Cat are subclasses of Animal that implement the abstract method make_sound.

Mixed Classes

An abstract class can have both abstract methods and concrete methods. Concrete methods provide a default implementation that can be inherited or overridden by subclasses.

Let’s see it with an example,

class Vehicle(ABC):
    @abstractmethod
    def drive(self):
        pass

    def start(self):
        print("The vehicle is started.")

class Car(Vehicle):
    def drive(self):
        print("The car is driving.")

class Motorcycle(Vehicle):
    def drive(self):
        print("The motorcycle is driving.")

In this example,

  • Vehicle has an abstract method drive and a concrete method start.
  • The subclasses Car and Motorcycle implement drive but inherit start.