ABC Module

Carson West

Abstract Classes

Python Notes: ABC Module

Current String: [ABC Module](./../abc-module/)

Full List: ['[ABC Module](./../abc-module/)']]

The ABC module in Python stands for Abstract Base Classes. It’s used to define interfaces for classes. This means you specify what methods a class must have, without specifying how those methods are implemented.

Key Concepts:

Example:

from abc import ABC, abstractmethod

class Shape(ABC): # Declare Shape as an abstract base class
    @abstractmethod
    def area(self):
        pass  # Abstract method - no implementation needed here

    @abstractmethod
    def perimeter(self):
        pass # Abstract method - no implementation needed here

class Circle(Shape):
    def __init__(self, radius):
        self.radius = radius

    def area(self):
        return 3.14159 * self.radius * self.radius

    def perimeter(self):
        return 2 * 3.14159 * self.radius

class Rectangle(Shape):
    def __init__(self,width, height):
        self.width = width
        self.height = height
    
    def area(self):
        return self.width * self.height
    
    def perimeter(self):
        return 2*(self.width + self.height)

#This will raise a TypeError because Shape is an abstract class
#shape = Shape()

circle = Circle(5)
print(f"Circle Area: {circle.area()}")
print(f"Circle Perimeter: {circle.perimeter()}")

rectangle = Rectangle(4,6)
print(f"Rectangle Area: {rectangle.area()}")
print(f"Rectangle Perimeter: {rectangle.perimeter()}")

Related Notes:

Further points to consider: