Abstract class

2 snippets across 2 stacks - Python, TypeScript

PYPython

Abstract Base Classes

PY · Classes & OOP
Syntax
from abc import ABC, abstractmethod
class Base(ABC):
    @abstractmethod
    def method(self): ...
Example
from abc import ABC, abstractmethod

class Shape(ABC):
    @abstractmethod
    def area(self) -> float: ...

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

    def area(self) -> float:
        return 3.14159 * self.radius ** 2

# shape = Shape()  # TypeError: can't instantiate abstract class
circle = Circle(5)
print(f"Area: {circle.area():.2f}")
Output
Area: 78.54

Note Abstract classes cannot be instantiated directly. Subclasses must implement all @abstractmethod methods or they will also be abstract.

TSTypeScript

Abstract Classes

TS · Classes
Syntax
abstract class Name {
  abstract method(): Type;
  concreteMethod(): Type { ... }
}
Example
abstract class Shape {
  abstract area(): number;
  abstract perimeter(): number;

  describe(): string {
    return `Area: ${this.area().toFixed(2)}, Perimeter: ${this.perimeter().toFixed(2)}`;
  }
}

class Circle extends Shape {
  constructor(private radius: number) {
    super();
  }

  area(): number {
    return Math.PI * this.radius ** 2;
  }

  perimeter(): number {
    return 2 * Math.PI * this.radius;
  }
}

// const shape = new Shape(); // Error: Cannot instantiate abstract class
const circle = new Circle(5);
console.log(circle.describe());
Output
// "Area: 78.54, Perimeter: 31.42"

Note Abstract classes cannot be instantiated directly. They can contain both abstract members (no implementation - subclasses must provide them) and concrete members (shared implementation). Use abstract classes when subclasses share behavior; use interfaces when they only share shape.

Frequently asked questions

How does Python handle abstract class?
This task is covered in 2 stacks on this page: Python, TypeScript. The "Abstract Base Classes" snippet in Python uses `from abc import ABC, abstractmethod`.
Which code does the Python example use?
The "Abstract Base Classes" snippet uses `from abc import ABC, abstractmethod`, from the Classes & OOP section of the Python cheat sheet.
Which stacks cover "abstract class" on this page?
Python, TypeScript. Together they hold 2 copy-ready snippets for this task.
Is there anything to watch out for?
Yes. For "Abstract Base Classes": Abstract classes cannot be instantiated directly. Subclasses must implement all @abstractmethod methods or they will also be abstract.