An abstract class is a blueprint for related classes. It can't be instantiated but can only be accessed through inheritance. A subclass that inherits an abstract class is required to implement its abstract methods. Otherwise, the compiler will flag an error.

Abstract methods are methods without implementation. An abstract class can have abstract methods or concrete (normal) methods.

Python doesn't directly support abstract methods, but you can access them through the abc (abstract base class) module.

Using the abc Module in Python

To define an abstract class in Python, you need to import the abc module.

See the example below:

from abc import ABC

class AbstractClassName(ABC):
   pass

Notice the keyword pass. This keyword is used to stand in for empty code. Leaving it out will give a compilation error.

Related: Will Julia Make a Bid for Python’s Throne?

Class definitions, method definitions, loops, and if statements expect code implementations. So, leaving them out gives a compilation error. To avoid this, use pass to substitute the empty code.

To define an abstract method in Python, use the @abstractmethod decorator:

from abc import ABC, abstractmethod

class AbstractClassName(ABC):

   @abstractmethod
   def abstractMethod(self):
       pass

At this point, it would be good to mention that—unlike Java—abstract methods in Python can have an implementation.. This implementation can be accessed in the overriding method using the super() method.

import abc

class AbstractClass(ABC):
     def __init__(self, value):
       self.value = value
       super().__init__()   

   @abc.abstractmethod
   def some_action(self):
       print("This is the parent implementation.")

class MySubclass(AbstractClassExample):
   def some_action(self):
       super().some_action()
       print("This is the subclass implementation. ")

x = MySubclass()
x.some_action()

It's interesting to note that you can define a constructor in an abstract class.

On line 9, you can observe that @abc.abstractmethod has been used as the abstract method decorator. This is another way of doing so other than the previous form. Notice also that line 1 is shorter (import abc) than the former line 1 import that you used.

It's all a matter of choice. Though, many may find the second method shorter.

Exception Handling in Python

Notice that there's no way to capture errors in the code example given above. Bugs occur more often than not, and having a reliable way to get them can be a game-changer.

These events that disrupt normal program flow are called "exceptions", and managing them is called "exception handling." Next on your Python reading list should be exception handling.