python键入模块:Mixin [英] python typing module: Mixin
问题描述
在typing
下是否有任何类的行为像mixin?
Is there any class under typing
that behaves like a mixin?
例如
from typing import Union
class A:
pass
class B:
pass
class C:
pass
class D(A, B, C):
pass
# current: ab is A or B, but not both
def f(ab: Union[A, B]):
pass
# ideal: ab is A and B
def f(ab: Mixin[A, B]):
pass
f(D())
请注意D
是A
和B
的实例,也是C
的实例.对f
的限制太大了(因为f
不需要C
),因此参数ab
不一定是D
类型,而是Mixin[A, B]
please notice how D
is instance of A
and B
, but also C
. This would be too much of a restriction for f
(since f
doesn't require C
) and thus, the parameter ab
is not necessarily of type D
but Mixin[A, B]
如果typing
模块不提供任何选项,那么还有什么比创建我自己的class AB(A, B)
更优雅的了?
If the typing
module doesn't provide any option, is there anything more elegant than creating my own class AB(A, B)
?
推荐答案
目前看来不可能.
您可以在 python/typing#123 存储库.
PEP-544 上有一个类似的功能,称为 Protocol ,您可以通过合并mixin协议来合并mixin. 有 PEP-544 的实现,称为
There is a similar feature on PEP-544 called Protocol, and you can merge mixins by merging mixin protocols. There is an implementation of PEP-544 called typing_extensions. Maybe you can try that with this library.
这篇关于python键入模块:Mixin的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!