Python抽象基类和多重继承 [英] Python abstract base classes and multiple inheritance

查看:115
本文介绍了Python抽象基类和多重继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个python(3.5)类结构,在其中我使用抽象方法来指示应实现的方法.预期效果如下:

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

当我向Derived添加一个类时,它不再起作用.此处显示为tuple(在我的具体情况下,我想使用np.ndarray):

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

Python中的抽象基类是否不打算用于多重继承?当然,我可以添加老式的NotImplementedError,但是只有在调用该方法时才会引发错误.

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.

推荐答案

从抽象类派生的类不能实例化除非所有其抽象方法都被覆盖.

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

这篇关于Python抽象基类和多重继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆