Python: __init__ abstract class

I am trying to declare an abstract class as a Aconstructor with standard behavior: all subclasses must initialize the element self.n:

from abc import ABCMeta

class A(object):
    __metaclass__ = ABCMeta

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

However, I do not want the class to Abe created, because, well, this is an abstract class. The problem is that this is really resolved:

a = A(3)

This does not cause errors when I expect this to happen.

So: how can I define a non-intuitive abstract class by defining default behavior for the constructor?

+22
source share
4 answers

Creating an __init__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)

It also works:

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

, @abc.abstractmethod.

+3

You can override the method __new__to prevent direct instantiation.

class A(object):
    __metaclass__ = ABCMeta

    def __new__(cls, *args, **kwargs):
        if cls is A:
            raise TypeError(
                "TypeError: Can't instantiate abstract class {name} directly".format(name=cls.__name__)
            )
        return object.__new__(cls)

Conclusion:

>>> A()
Traceback (most recent call last):
  File "<ipython-input-8-3cd318a12eea>", line 1, in <module>
    A()
  File "/Users/ashwini/py/so.py", line 11, in __new__
    "TypeError: Can't instantiate abstract class {name} directly".format(name=cls.__name__)
TypeError: TypeError: Can't instantiate abstract class A directly
+3
source

A not-so-elegant solution might be this:

class A(object):
  def __init__(self, n):
    if self.__class__ == A:
      raise Exception('I am abstract!')
    self.n = n

Using

class B(A):
  pass
a = A(1)  # Will throw exception
b = B(1)  # Works fine as expected.
+2
source

Source: https://habr.com/ru/post/1680299/


All Articles