Placement Prep

Abstraction in Python: Abstract Classes and the ABC Module

Use Python's ABC module to create abstract classes that enforce method contracts. Includes working code, a common error walkthrough, and placement-round tips.

By FACE Prep Team 6 min read
python abstraction abc-module oop abstract-class placement-prep programming

Abstraction in Python lets you define what a class must do without specifying how it does it, and the ABC module makes that contract enforceable at runtime.

What Abstraction Means in Code

Abstraction is the practice of exposing only what a user of your code needs to know, while hiding the internal mechanism. Every time you call len([1, 2, 3]), you’re using abstraction: you get the count back without knowing whether Python stored it as a field or recomputed it by traversal.

In object-oriented design, abstraction usually shows up as a base class that defines a set of methods without filling in their bodies. Derived classes then fill in those bodies according to their own logic. The base class sets the contract; the derived classes honour it.

Two real-world illustrations make this concrete:

  • A TV remote defines a set of buttons: volume up, channel change, power. You don’t need to know whether the remote uses infrared or Bluetooth. The button is the contract; the hardware is the implementation.
  • A payment gateway defines a charge(amount) method. The gateway SDK doesn’t care whether you’re using Razorpay, PayU, or Cashfree underneath. Each payment provider implements charge in its own way; the rest of the application calls it identically.

Python implements this pattern through abstract classes. An abstract class defines one or more method signatures without providing a body. Any class that inherits from it must implement every abstract method before Python lets you create an instance.

For a broader grounding in Python before tackling OOP patterns, Python practice programs is a useful starting point.

Abstract Classes with the ABC Module

Python’s standard library ships a module called abc (Abstract Base Classes) for exactly this purpose. The Python abc module documentation covers the full API; the two things you need for everyday use are:

  • ABC: the base class to inherit from when defining an abstract class.
  • abstractmethod: the decorator to mark a method as abstract (no body required).

The import line is always:

from abc import ABC, abstractmethod

A minimal abstract class looks like this:

from abc import ABC, abstractmethod

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

Shape inherits from ABC, which registers it with Python’s metaclass machinery. The @abstractmethod decorator tells Python that any concrete (non-abstract) class inheriting from Shape must provide its own calculate_area method.

Attempting to instantiate Shape directly raises an error immediately:

s = Shape()  # TypeError: Can't instantiate abstract class Shape with abstract method calculate_area

The error is informative on purpose: it names the class and the unimplemented method.

According to the Python glossary entry for abstract base class, abstract base classes complement duck typing by providing a formal way to define interfaces and check whether an object conforms to one, using isinstance() checks that carry semantic meaning beyond attribute lookup.

Implementing Abstract Methods in Derived Classes

A derived class satisfies the abstract class contract by providing a concrete implementation for every abstract method. Here is a full working example with two shapes:

from abc import ABC, abstractmethod

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

class Rectangle(Shape):
    def __init__(self, length, breadth):
        self.length = length
        self.breadth = breadth

    def calculate_area(self):
        return self.length * self.breadth

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

    def calculate_area(self):
        return 3.14 * self.radius * self.radius

rec = Rectangle(5, 3)
cir = Circle(4)

print("Area of rectangle:", rec.calculate_area())
print("Area of circle:", cir.calculate_area())

Output:

Area of rectangle: 15
Area of circle: 50.24

Verification of the arithmetic:

  • Rectangle: 5 * 3 = 15
  • Circle: 3.14 * 4 * 4 = 3.14 * 16 = 50.24

Each derived class gets its own __init__, accepting the specific parameters that make sense for that shape. Rectangle needs length and breadth; Circle needs radius. The abstract class imposes no constraint on __init__; only calculate_area must be implemented.

This design pattern is common in placement technical rounds. Companies that ask OOP questions often use the shape hierarchy as a starting point and then extend it: add a Triangle, add a perimeter method, add validation for negative dimensions. The abstraction layer means that adding a Triangle class never touches Rectangle or Circle.

For comparison, the simple calculator program uses a similar principle at a smaller scale: each operation branch isolates its logic from the others. Abstract classes generalise that separation into a class hierarchy.

Mixing Regular and Abstract Methods

An abstract class is not limited to abstract methods. It can include fully implemented regular methods that all derived classes inherit automatically.

from abc import ABC, abstractmethod

class Shape(ABC):
    def describe(self):
        print("This is a Shape object.")

    @abstractmethod
    def calculate_area(self):
        pass

class Rectangle(Shape):
    def __init__(self, length, breadth):
        self.length = length
        self.breadth = breadth

    def calculate_area(self):
        return self.length * self.breadth

rec = Rectangle(5, 3)
rec.describe()
print("Area:", rec.calculate_area())

Output:

This is a Shape object.
Area: 15

The describe method is defined once in Shape and inherited by Rectangle. There is no need to repeat it in the derived class unless you want to override its behaviour.

This pattern is useful for shared utility methods. Suppose every shape needs a method to log its area to a file, or to return a dictionary representation for a JSON API. Define that once in the abstract class. The abstract method calculate_area ensures every shape provides the number the shared utilities depend on.

Real codebases use this extensively. A DatabaseConnector abstract class might implement execute_query as a regular method, while connect and disconnect are abstract. The query-running logic is shared; the connection protocol is database-specific.

What Happens When a Derived Class Skips an Abstract Method

If a derived class does not implement all abstract methods, Python treats it as abstract too. You cannot instantiate it.

from abc import ABC, abstractmethod

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

class BadShape(Shape):
    pass  # forgot to implement calculate_area

b = BadShape()
# TypeError: Can't instantiate abstract class BadShape with abstract method calculate_area

The error fires at BadShape() (the instantiation call), not at the moment Python parses the class definition. This means BadShape can exist as a class object without error. You just can’t create an instance of it.

This distinction matters most when writing a library or framework. Other developers can define intermediate classes that add shared state without implementing the full interface. The final concrete class in the hierarchy must satisfy every abstract method.

The sum-of-array problem from sum of array in Python is a useful contrast: it shows how Python errors propagate at runtime without OOP overhead, which helps you understand what the TypeError message means when you first encounter it here.

Abstraction in Placement Coding Rounds

Placement coders encounter abstraction in two contexts: written MCQ sections and technical interview discussions.

In MCQ sections, the common question types are:

  • “What happens when you instantiate an abstract class?” — TypeError at runtime (not a syntax error, not a NameError).
  • “Which module provides the ABC class?” — the abc module.
  • “Does an abstract class have to be 100% abstract?” — No. It can contain regular methods.
  • “What decorator marks a method as abstract?” — @abstractmethod.

In technical interviews, the question is often conceptual: “Why would you use an abstract class instead of just a regular class?” The answer centres on enforceability. A regular class with an empty calculate_area method (using pass) compiles fine, but a derived class that forgets to override it will silently return None instead of a number. An abstract class makes the contract explicit and lets Python catch the omission at instantiation time rather than at the calculation step.

The broader OOP question (“what are the four pillars of object-oriented programming?”) always includes abstraction alongside encapsulation, inheritance, and polymorphism. Interviewers at service companies often ask you to implement a simple example. The shape hierarchy with the ABC module is the standard demonstration.


The ABC module is fundamentally about interfaces: defining what a component must expose so the rest of a system can rely on it. That same discipline matters when building with LLMs. Every tool in an LLM agent has a defined interface (inputs, outputs, error contract), and the LLM coordinates across those interfaces without knowing their internals. If you want to build and iterate on those patterns in Python, TinkerLLM provides a working environment to do that at ₹299.

Primary sources

Frequently asked questions

Can an abstract class have a constructor in Python?

Yes. An abstract class can define __init__ just like a regular class. Derived classes call it via super().__init__() if needed. The restriction is only on instantiating the abstract class directly.

What happens if I try to instantiate an abstract class?

Python raises a TypeError with the message: 'Can't instantiate abstract class X with abstract method y'. This is enforced at the instantiation call, not when the class is defined.

What is the difference between an abstract class and an interface in Python?

Python has no formal interface keyword. An abstract class with only abstract methods and no implementation acts like an interface. In practice, Python developers use ABC subclasses for both roles — the distinction is a design choice, not a language rule.

Can a derived class also be abstract?

Yes. If a derived class does not implement all abstract methods from its parent, Python treats it as abstract too. You cannot instantiate it until all abstract methods are implemented somewhere in the chain.

Do I need to import abstractmethod separately from ABC?

Yes. The import is: from abc import ABC, abstractmethod. ABC is the base class; abstractmethod is the decorator. Both are in the same module but must be named explicitly in the import.

Why use abstract classes instead of regular classes with empty methods?

An empty method with pass allows a derived class to skip implementing it without any error. An abstract method enforces implementation at instantiation time. Abstract classes make the contract explicit and machine-checked.

Build AI projects

A self-paced playground for building with LLMs.

TinkerLLM is FACE Prep's sister property. A guided environment for shipping real LLM applications, the kind of project that earns a paragraph on your resume, not a line.

Try TinkerLLM (₹299 launch)
Free AI Roadmap PDF