如何在Python类型提示中表达多重继承?

Ale*_*Lee 10 python python-typing

在Java C#中,泛型方法可以具有带约束的类型参数,以定义必须实现的接口。

static <T extends Iterable<Integer> & Comparable<Integer>> void test(T p) {

}
Run Code Online (Sandbox Code Playgroud)

在Python中,如果我想使用类型提示来指定变量必须继承类A和B,我该怎么做?我检查了输入模块,它只有一个Union,这意味着变量的类型可以是任何提示,而不能是所有提示。

创建一个继承A和B的新类C似乎是一个解决方案,但看起来很麻烦。

小智 3

该类定义相当于:

class MyIter(Iterator[T], Generic[T]):
    ...
Run Code Online (Sandbox Code Playgroud)

您可以将多重继承与泛型一起使用:

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]):
    ...
Run Code Online (Sandbox Code Playgroud)

在不指定类型参数的情况下对泛型类进行子类化假定每个位置都为 Any。在下面的示例中,MyIterable 不是通用的,而是隐式继承自 Iterable[Any]:

from typing import Iterable

class MyIterable(Iterable):  # Same as Iterable[Any]
    ...
Run Code Online (Sandbox Code Playgroud)

不支持通用元类。