首页 > 解决方案 > TypeVar 描述一个必须子类化多个类的类

问题描述

我想创建一个类型注释T来描述一个类型,该类型必须是 classA和 class的子类B

T = TypeVar('T', bound=A)仅指定T必须是 的子类A

T = TypeVar('T', A, B)仅指定T必须是的子类A或子类,B不一定是两者。

我实际上想要类似的东西T = TypeVar('T', bound=[A, B]),这意味着T必须同时继承AB. 有这样做的标准方法吗?

标签: pythonpython-3.xtype-hintingpython-typing

解决方案


您正在寻找的是一个交叉点类型。严格来说,我不相信 Python 的类型注释支持这一点(至少现在还没有)。但是,您可以通过 a 获得类似的东西Protocol

from typing import Protocol, TypeVar

class A:
    def foo(self) -> int:
        return 42
class B:
    def bar(self) -> bool:
        return False

class C(A, B): pass
class D(A): pass
class E(B): pass

class ABProtocol(Protocol):
    def foo(self) -> int: ...
    def bar(self) -> bool: ...

T = TypeVar('T', bound=ABProtocol)

def frobnicate(obj: T) -> int:
    if obj.bar():
        return obj.foo()
    return 0

frobnicate(C())
frobnicate(D())
frobnicate(E())

Mypy抱怨:

test.py:26: error: Value of type variable "T" of "frobnicate" cannot be "D"
test.py:27: error: Value of type variable "T" of "frobnicate" cannot be "E"

当然,这需要您自己显式注释所有方法,不幸的class ABProtocol(A, B, Protocol): pass是,不允许使用类似的东西


推荐阅读