Search code examples
pythonoopabstract-classabc

Understanding Abstract Base Classes in Python


I was reading about abstract base class and came across https://www.python-course.eu/python3_abstract_classes.php website. I got general idea about them but I found two statement contradictory of each other.

Subclasses of an abstract class in Python are not required to implement abstract methods of the parent class.

and

A class that is derived from an abstract class cannot be instantiated unless all of its abstract methods are overridden.

My understanding of first statement is, derived class are not required to implement abstract method of the parent class which is wrong. I made a sample program to check that.

from abc import ABC, abstractmethod

class AbstractClassExample(ABC):

    @abstractmethod
    def do_something(self):
        print("Some implementation!")

class AnotherSubclass(AbstractClassExample):

    def just_another_method(self):
        super().do_something()
        print("The enrichment from AnotherSubclass")

x = AnotherSubclass() # TypeError: Can't instantiate abstract class AnotherSubclass with abstract methods do_something
x.do_something()

I would like an explanation of what the first statement means(preferably with examples).


Solution

  • Your code demonstrates that the second statement is true. It doesn't show that the first statement is false.

    In your code, you are trying to instantiate AnotherSubclass, which is not allowed because AnotherSubclass does not implement all the abstract methods. The second statement says this.

    However, if you delete the last two lines, i.e. not instantiating AnotherSubclass, then your code will produce no errors when you try to run it. This shows that the first statement is true - subclasses of abstract classes that doesn't implement all its abstract methods are allowed to exist.

    You can write another subclass of AnotherSubclass called YetAnotherClass, this time implementing the abstract method, and you will be able to instantiate YetAnotherClass. Note that your program now does something, and AnotherSubclass is still allowed to exist.