How define constructor implementation for an Abstract Class in Python?

dabadaba picture dabadaba · Jun 28, 2017 · Viewed 33.5k times · Source

I am trying to declare an abstract class A with a constructor with a default behavior: all subclasses must initialize a member self.n:

from abc import ABCMeta

class A(object):
    __metaclass__ = ABCMeta

    def __init__(self, n):
        self.n = n

However, I do not want to let the A class be instantiated because, well, it is an abstract class. The problem is, this is actually allowed:

a = A(3)

This produces no errors, when I would expect it should.

So: how can I define an un-instantiable abstract class while defining a default behavior for the constructor?

Answer

Mike Müller picture Mike Müller · Jun 28, 2017

Making the __init__ an abstract method:

from abc import ABCMeta, abstractmethod

class A(object):
    __metaclass__ = ABCMeta

    @abstractmethod
    def __init__(self, n):
        self.n = n


if __name__ == '__main__':
    a = A(3)

helps:

TypeError: Can't instantiate abstract class A with abstract methods __init__

Python 3 version:

from abc import ABCMeta, abstractmethod

class A(object, metaclass=ABCMeta):

    @abstractmethod
    def __init__(self, n):
        self.n = n


if __name__ == '__main__':
    a = A(3)

Works as well:

TypeError: Can't instantiate abstract class A with abstract methods __init__