如何解决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似乎通过其编辑器类型检查来支持它。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。