问题
I am trying to create a python (3.5) class structure where I use abstract methods to indicate which methods should be implemented. The following works as expected:
from abc import ABC, abstractmethod
class Base(ABC):
@abstractmethod
def foo(self):
pass
class Derived(Base, object):
# Inheriting from object probably is superfluous (?)
pass
Derived() # throws a TypeError
When I add a class to Derived
, it does not work anymore. Here shown with a tuple
(in my specific case I want to use a np.ndarray
):
class Base(ABC):
@abstractmethod
def foo(self):
pass
class Derived(Base, tuple):
pass
Derived() # does not throw an error
Are abstract base classes in python not intended for multiple inheritance? Of course I could add old-school NotImplementedError
s, but then an error is only thrown when the method is called.
回答1:
A class that is derived from an abstract class cannot be instantiated unless all of its abstract methods are overridden.
from abc import ABC, abstractmethod
class Base(ABC):
@abstractmethod
def foo(self):
pass
class Derived(Base):
# Need to implement your abstract method: foo()
def foo(self): # <-- add this
pass
Derived() # Runs ok
来源:https://stackoverflow.com/questions/60015859/python-abstract-base-classes-and-multiple-inheritance