How define constructor implementation for an Abstract Class in Python?
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__
A not so elegant solution can be this:
class A(object):
def __init__(self, n):
if self.__class__ == A:
raise Exception('I am abstract!')
self.n = n
Usage
class B(A):
pass
a = A(1) # Will throw exception
b = B(1) # Works fine as expected.