Ask Your Question

Revision history [back]

  1. Define at least one abstract method in the class. This will force any subclass to implement the abstract method before it can be instantiated.

  2. Make the class itself abstract by adding the abstract keyword before the class definition. This will prevent the class from being instantiated directly, but will still allow subclassing and instantiation of the subclass.

  3. Implement a private constructor method for the class and raise an exception if it is called. This will prevent the class from being instantiated directly and force a subclass to implement its own constructor.

Example:

from abc import ABC, abstractmethod

class MyClass(ABC):

  # Define at least one abstract method
  @abstractmethod
  def my_method(self):
    pass

  # Make the class abstract
  @classmethod
  def __subclasshook__(cls, C):
    if cls is MyClass:
      if any("my_method" in B.__dict__ for B in C.__mro__):
        return True
    return NotImplemented

  # Implement a private constructor method
  def __init__(self):
    raise Exception("MyClass cannot be instantiated directly")

class MySubClass(MyClass):

  # Implement the abstract method
  def my_method(self):
    print("MySubClass method called")

# This will raise an exception
my_class = MyClass()

# This will work
my_subclass = MySubClass()
my_subclass.my_method()