how to inherit and enforce an abstract method defined in a superclass with __metaclass__ = ABCMeta

100 views Asked by At

There is class A (in another package) that defines an abstract method my_abstract_method() using the old way of defining an abstract class by setting __metaclass__ = ABCMeta.

My class B is a subclass of A, and I would like B to inherit A's my_abstact_method(), and require all subclasses of B to implement my_abstract_method()

How would I go about doing this?

Example:

from abc import abstractmethod, ABC, ABCMeta


class A(object):
    __metaclass__ = ABCMeta

    @abstractmethod
    def my_abstract_method(self):
        return

class B(A, metaclass=ABCMeta):

    pass

B()

When executed, B() is created successfully.

How can I get B() to fail because the abstract method of A is not defined?

1

There are 1 answers

1
Logain On

EDIT: It's hard to grasp what the issue here is, apart from the obvious - the below solution might or might be relevant for the actual implementation.

The below solution introduces another layer of abstraction, which breaks the principle "the solution to inheritance is not more inheritance", but this might be a special case where it might be useful for your scenario.

from abc import abstractmethod, ABC, ABCMeta


class A(object):
    __metaclass__ = ABCMeta

    @abstractmethod
    def my_abstract_method(self):
        return


class C(A, ABC):    
    @abstractmethod
    def new_abstract_method(self):
        pass


class B(C):
    pass
    

B()