1. LPU MCA Semester 1
  2. CAB106
  3. Unit 4

CAB106 · Unit 4: Abstraction, modules and packages

Abstract classes, abstract methods, the ABC module and interfaces

11 practice questions

Key points

  • Inherit ABC and mark methods with @abstractmethod
  • A class with unimplemented abstract methods cannot be instantiated
  • Subclasses must override every abstract method
  • An ABC of only abstract methods acts as an interface

Abstraction exposes what an object does and hides how. In Python an abstract base class (ABC) is created by inheriting from ABC in the abc module, and a method that subclasses must provide is marked @abstractmethod.

A class that still has an abstract method cannot be instantiated: Shape() raises TypeError. A subclass stays abstract until it overrides every abstract method; once it does, it can be instantiated and isinstance(obj, Shape) is True. An abstract class can also contain ordinary methods that use the abstract ones, so the base fixes the steps and each subclass fills in the details (the template method idea). An abstract method may even have a body, which a subclass can call through super(). Abstract properties are written with @property above @abstractmethod.

Python has no interface keyword. An ABC made entirely of abstract methods is used as an interface, defining which methods an object must offer. A class derived from ABC that has no abstract methods can be instantiated normally.

Exam trap: inheriting from ABC is not what blocks instantiation. The unimplemented @abstractmethod is.

Try two questions

Question 1 · Tier 2, Understand

Python has no interface keyword. What is the usual way to define an interface?

  1. A class that declares the keyword interface before its name
  2. A module that contains only constants and no classes
  3. A function decorated so that it cannot be called
  4. An abstract base class in which every method is abstract
Show the answer

D. An ABC made only of abstract methods plays the role of an interface.

Why not A: Python has no interface keyword.

Why not B: A module of constants defines no required methods.

Why not C: A non-callable function does not describe the methods an object must have.

Question 2 · Tier 1, Recall

Which decorator marks a method that every concrete subclass must implement?

  1. @override
  2. @abstract
  3. @required
  4. @abstractmethod
Show the answer

D. @abstractmethod from the abc module stops a subclass from being instantiated until it overrides the method.

Why not A: @override is not a built-in Python decorator.

Why not B: The correct name is abstractmethod, not abstract.

Why not C: Python has no decorator called required.