close

How define constructor implementation for an Abstract Class in Python?

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How define constructor implementation for an Abstract Class in Python in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How define constructor implementation for an Abstract Class in Python?

  1. 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

  2. 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

Method 1

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__

Method 2

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.

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read