简体   繁体   English

python ABC & 多个 Inheritance

[英]python ABC & Multiple Inheritance

I would like to know if it is possible to use multiple inheritance with abstract base class in python.我想知道是否可以在 python 中使用多个 inheritance 和抽象基 class。 It seems like it should be possible but can't find a statement one way or the other.似乎应该是可能的,但无法以一种或另一种方式找到陈述。

The basic ABC example:基本的 ABC 示例:


from abc import ABC, abstractmethod


class BaseABC(ABC):

    @abstractmethod
    def hello(self):
        pass


class Child(BaseABC):
    pass


child = Child()

This will fail due to "hello" not being implemented in "Child".由于“你好”没有在“孩子”中实现,这将失败。

What I would like is to know how to combine ABC with multiple inheritance.我想知道如何将ABC与多个inheritance结合起来。 I would like to make either the "BaseABC" or "Child" to inherit also from some other separate class.我想让“BaseABC”或“Child”也从其他一些单独的 class 继承。 Explicitly:明确地:


from abc import ABC, abstractmethod


class BaseABC(ABC, dict):

    @abstractmethod
    def hello(self):
        pass


class Child(BaseABC):
    pass


child = Child()

This does not fail in the way expected as the first case does.这不会像第一种情况那样以预期的方式失败。 Also:还:


from abc import ABC, abstractmethod


class BaseABC(ABC):

    @abstractmethod
    def hello(self):
        pass


class Child(BaseABC, dict):
    pass


child = Child()

This does not fail either.这也不会失败。 How can I require "Child" to implement "hello"?我怎样才能要求“孩子”来实现“你好”?

The issue is with inheriting from a dict, which is probably better explained by these guys:问题在于从 dict 继承,这些人可能更好地解释了这一点:

So depending on little what you want to do with your subclassed dict you could go with MutableMapping as suggested in https://stackoverflow.com/a/3387975/14536215 or with UserDict (which is a subclass of MutableMapping) such as:因此,根据您想对子类 dict 做什么,您可以使用 go 和MutableMapping ,如https://stackoverflow.com/a/3387975/14536215UserDict中建议的那样(这是 MutableMapping 的子类)

from abc import ABC, abstractmethod
from collections import UserDict


class BaseABC(ABC):

    @abstractmethod
    def hello(self):
        pass

class Child(BaseABC, UserDict):
    pass


child = Child()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM