Python abstract base classes and multiple inheritance [duplicate]

此生再无相见时 提交于 2020-02-24 18:59:50

问题


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 NotImplementedErrors, 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!