【问题标题】:Python multiple inheritance from class and protocolPython从类和协议的多重继承
【发布时间】:2021-10-31 01:42:26
【问题描述】:

在 Python 中,我有两个协议,其中一个继承自另一个:

class SupportsFileOperations(Protocol):
    ...

class SupportsMediaOperations(SupportsFileOperations):
    ...

然后我有几个实现这些协议的具体类,其中一个继承自另一个。

class File(SupportsFileOperations):
    ...

class MediaFile(File, SupportsMediaOperations):
    def __init__(self):
        File.__init__(self)

我的问题是,在MediaFile 构造函数中调用File.__init__(self) 是初始化它的正确方法吗?我不确定多重继承如何与协议一起使用。

谢谢!

【问题讨论】:

  • 在这种情况下,Protocol 是什么?对象来自哪个库?
  • 抱歉,这里使用的是from typing import Protocol

标签: python inheritance protocols


【解决方案1】:

您可以在子类中简单地添加Protocol

from typing import Protocol

class SupportsFileOperations(Protocol):
    ...

class SupportsMediaOperations(SupportsFileOperations, Protocol):
    ...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多