python - 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 是一个实际的类并且不能组合到协议中。
解决方案
我通过定义一个中间抽象类来解决它:
class MyMixedType(A,B):
pass
class C(MyMixedType):
# very specific implementation
def my_typed_function(param: MyMixedType):
...
但这只有效,因为我可以让所有类实现MyMixedType
,从而将多重继承卸载到上一层。
相关:如何验证一个类型是否有多个超类(感谢@khelwood)
在研究了这个问题和许多链接的 github 问题之后,这似乎是自 2018 年以来一直存在的问题。将调用一个解决方案,Intersection
但据我所知仍未实施。PyCharm/IntelliJ 似乎通过他们的编辑器类型检查来支持它。
推荐阅读
- javascript - 如何使所有滑块在一条垂直线上?
- performance - 对于在动态游戏场上拥有大量 AI 的游戏来说,哪种导航方法最高效、最灵活?
- node.js - Express Flash 消息不适用于 Axios,但适用于 Postman。这是为什么?
- amazon-s3 - 在不下载完整文件的情况下使用 FFMPEG
- arrays - iOS如何找到浮点/整数值数组的值之间的最小差异
- python - 如何在叠加散点图上注释(标签)?
- javascript - 在javascript中对混合服装尺寸的数组进行排序
- sql - 如果在 SQL 查询中满足特定条件,有没有办法只返回某些值?
- javascript - 使用提供的 id 删除数组中的对象
- c# - WeakReference 在 .Net Framework 和 .Net Core 之间的行为不同