首页 > 解决方案 > Python键入多重继承作为参数

问题描述

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

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)

我还研究了键入协议并将 A 定义为协议,但遇到了同样的问题,因为 B 是一个实际的类并且不能组合到协议中。

标签: pythonmultiple-inheritancemypypython-typing

解决方案


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

class MyMixedType(A,B):
    pass

class C(MyMixedType):
    # very specific implementation

def my_typed_function(param: MyMixedType):
    ...

这只有效,因为我可以让所有类实现MyMixedType,从而将多重继承卸载到上一层。

相关:如何验证一个类型是否有多个超类(感谢@khelwood)
在研究了这个问题和许多链接的 github 问题之后,这似乎是自 2018 年以来一直存在的问题。将调用一个解决方案,Intersection但据我所知仍未实施。PyCharm/IntelliJ 似乎通过他们的编辑器类型检查来支持它。


推荐阅读