【问题标题】:Python typing multiple inheritance as parameterPython键入多重继承作为参数
【发布时间】:2020-09-02 12:33:19
【问题描述】:

我想显式键入一个需要从两个类继承的函数参数。 示例:

class SomeInterface:
    def first_function():
        pass

class SuperClass:
    def other_function():
        # implementation here
    # more function definitions

class C(A, B):
    # overrides first_function

def my_typed_function(param: Union[A,B]):
    param.first_function() # mypy: variant B does not have that function
    param.other_function() # mypy: variant A does not have that function

我可以用什么来代替Union 来显示这种关系? (请记住,也可能有其他实现,如 C 传递给它,所以我不能显式使用 C)

我还查看了typing protocols 并将 A 定义为协议,但遇到了同样的问题,因为 B 是一个实际的类并且不能合并到协议中。

【问题讨论】:

  • 这不是C 的用途吗? def my_typed_function(param: C):如果你可以有多个实现,也许它们应该是C的子类。
  • 可能还有一个 D 实现了这两件事,我不一定能控制它。这就是为什么我想要通用
  • 您可能只想定义一个支持first_functionother_function 的协议,而不引用SomeInterfaceSuperClass
  • 应该可以做但是有点难看,因为我想用超类的很多功能,感觉非常多余

标签: python multiple-inheritance mypy python-typing


【解决方案1】:

我通过定义一个中间抽象类来解决它:

class MyMixedType(A,B):
    pass

class C(MyMixedType):
    # very specific implementation

def my_typed_function(param: MyMixedType):
    ...

但是这仅适用于我可以让所有类实现MyMixedType,从而将多重继承卸载到上一层。

相关:how to verify a type has multiple super classes(感谢@khelwood)
在研究了这个问题和许多链接的 github 问题之后,这似乎是自 2018 年以来一直存在的问题。一个解决方案将被称为Intersection,但据我所知仍未实施。 PyCharm/IntelliJ 似乎通过他们的编辑器类型检查来支持它。

【讨论】:

    猜你喜欢
    • 2019-09-25
    • 2015-05-04
    • 2020-12-18
    • 2021-08-05
    • 1970-01-01
    • 2015-06-01
    • 1970-01-01
    • 2021-05-16
    • 2015-05-02
    相关资源
    最近更新 更多