86

Suppose I have a base class with unimplemented methods as follows:

class Polygon():
    def __init__(self):
        pass

    def perimeter(self):
        pass

    def area(self):
        pass

Now, let's say one of my colleagues uses the Polygon class to create a subclass as follows:

import math

class Circle(Polygon):
    def __init__(self, radius):
        self.radius = radius

    def perimeter(self):
        return 2 * math.pi * self.radius

(H/Sh)e has forgotten to implement the area() method.

How can I force the subclass to implement the parent's area() method?

Aditya Barve
  • 1,351
  • 1
  • 9
  • 13

3 Answers3

156

this could be your parent class:

class Polygon():

    def __init__(self):
        raise NotImplementedError

    def perimeter(self):
        raise NotImplementedError

    def area(self):
        raise NotImplementedError

although the problem will be spotted at runtime only, when one of the instances of the child classes tries to call one of these methods.


a different version is to use abc.abstractmethod.

from abc import ABC, abstractmethod
import math


class Polygon(ABC):

    @abstractmethod
    def __init__(self):
        pass

    @abstractmethod
    def perimeter(self):
        pass

    @abstractmethod
    def area(self):
        pass

class Circle(Polygon):
    def __init__(self, radius):
        self.radius = radius

    def perimeter(self):
        return 2 * math.pi * self.radius

#    def area(self):
#        return math.pi * self.radius**2


c = Circle(9.0)
# TypeError: Can't instantiate abstract class Circle
#            with abstract methods area

you will not be able to instantiate a Circle without it having all the methods implemented.

this is the python 3 syntax; in python 2 you'd need to

class Polygon(object):
    __metaclass__ = ABCMeta

also note that for the binary special functions __eq__(), __lt__(), __add__(), ... it is better to return NotImplemented instead of raising NotImplementedError.

hiro protagonist
  • 44,693
  • 14
  • 86
  • 111
  • 1
    I would put your 2nd option as the primary, letting the 1st an alternative option with drawbacks. Following the Zen of python I would only keep the simple version of your 2nd option since it is simpler and works just fine. – thanos.a Feb 17 '21 at 14:27
  • Is there anyway to enforce return type / type hint on overridden method? – Validus Oculus May 04 '23 at 03:05
  • no. python itself does not enforce any type hints. you need a static type checker for that. – hiro protagonist May 04 '23 at 05:42
7

You can raise NotImplementedError exception in base class method.

class Polygon:
    def area(self):
        raise NotImplementedError

Also you can use @abc.abstractmethod, but then you need to declare metaclass to be abc.ABCMeta, which would make your class abstract. More about abc module

vishes_shell
  • 22,409
  • 6
  • 71
  • 81
7

That's exactly what NotImplementedError are used for :)

In your base class

def area(self):
    raise NotImplementedError("Hey, Don't forget to implement the area!")
Yevhen Kuzmovych
  • 10,940
  • 7
  • 28
  • 48
  • 4
    This only works when you are trying to call the `area()` method. If you want to really force a user to implement all the methods, ABC module is needed. – pdaawr May 31 '21 at 10:42