Codzy

Abstraction

Abstraction means defining what an object must be able to do, without saying how. You create an abstract class with ABC and mark the required methods with @abstractmethod.

You can't create an object directly from an abstract class: you need a child class that writes all the abstract methods. It's a "contract" that guarantees every shape, employee or payment really has the expected methods.

from abc import ABC, abstractmethod

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

class Square(Shape):
    def __init__(self, side):
        self.side = side

    def area(self):
        return self.side ** 2

print(Square(4).area())
try:
    Shape()
except TypeError:
    print("Shape is abstract!")

Start the lesson