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)

我也研究了typing protocols并将A定义为协议,但是由于B是一个实际的类并且无法合并到协议中,因此遇到了同样的问题。

解决方法

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

class MyMixedType(A,B):
    pass

class C(MyMixedType):
    # very specific implementation

def my_typed_function(param: MyMixedType):
    ...

BUT 这只能工作,因为我可以让所有类都实现MyMixedType,从而将多重继承卸载到上面的一个级别。

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

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...