[英]How to express multiple inheritance in Python type hint?
在 Java、C# 中,泛型方法可以有一个带约束的类型参数来定义必须实现的接口。
static <T extends Iterable<Integer> & Comparable<Integer>> void test(T p) {
}
在Python中,如果我想使用类型提示来指定一个变量必须继承类A和B,我该怎么做? 我检查了输入模块,它只有一个联合,这意味着变量的类型可以是任何提示,而不是所有提示。
创建一个继承 A 和 B 的新类 C 似乎是一个解决方案,但看起来很麻烦。
该类定义等效于:
class MyIter(Iterator[T], Generic[T]):
...
您可以在 Generic 中使用多重继承:
from typing import TypeVar, Generic, Sized, Iterable, Container, Tuple
T = TypeVar('T')
class LinkedList(Sized, Generic[T]):
...
K = TypeVar('K')
V = TypeVar('V')
class MyMapping(Iterable[Tuple[K, V]],
Container[Tuple[K, V]],
Generic[K, V]):
...
在不指定类型参数的情况下对泛型类进行子类化,每个位置都假定为 Any。 在以下示例中,MyIterable 不是通用的,而是隐式继承自 Iterable[Any]:
from typing import Iterable
class MyIterable(Iterable): # Same as Iterable[Any]
...
不支持通用元类。
从技术上讲,您可以输入var: Class1 and Class2
以及var: (Class1, Class2)
,但是类型检查器无法正确解析它。 这段代码在Python 3.6上运行良好
class A:
pass
class B:
pass
def func_1(a: A, b: B, both: A and B):
pass
def func_2(a: A, b: B, both: (A, B)):
pass
这将导致:
func_1.__annotations__
{'a': <class '__main__.A'>, 'b': <class '__main__.B'>, 'both': <class '__main__.B'>}
func_2.__annotations__
{'a': <class '__main__.A'>, 'b': <class '__main__.B'>, 'both': (<class '__main__.A'>, <class '__main__.B'>)}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.