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:
Notice the keyword pass. This keyword is used to stand in for empty code. Leaving it out will give a compilation error.
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:
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.
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.