Module (71%)
Section (63%)

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 GreenField class and call the hello method, because the Python developer has provided a concrete definition of the hello method.

    In other words, the Python developer has overridden the abstract method hello with 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 TypeError exception when we try to instantiate the base BluePrint class, because it contains an abstract method.

Code

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()
{{ dockerServerErrorMsg }} ×
{{ errorMsg }} ×
{{ successMsg }} ×