Now we'll try to instantiate the BluePrint class:
import abc
class BluePrint(abc.ABC):
@abc.abstractmethod
def hello(self):
pass
class GreenField(BluePrint):
def hello(self):
print('Welcome to Green Field!')
gf = GreenField()
gf.hello()
bp = BluePrint()
The output:
Welcome to Green Field!
Traceback (most recent call last):
(...)
bp = BluePrint()
TypeError: Can't instantiate abstract class BluePrint with abstract methods hello
output
indicates that:
- it’s possible to instantiate the
GreenFieldclass and call thehellomethod, because the Python developer has provided a concrete definition of thehellomethod.In other words, the Python developer has overridden the abstract method
hellowith their own implementation. When the base class provides more abstract methods, all of them must be overridden in a subclass before the subclass can be instantiated. - Python raises a
TypeErrorexception when we try to instantiate the baseBluePrintclass, because it contains an abstract method.