python - 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
必须同时继承A
和B
. 有这样做的标准方法吗?
解决方案
您正在寻找的是一个交叉点类型。严格来说,我不相信 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
是,不允许使用类似的东西
推荐阅读
- bash - 纽曼运行过度填充缓存内存
- linux - docker container exec -i [container_name] stat -c '%a' /path
- java - 如何将微调器选定项目插入 SQL Server for mobile app?
- python - 正则表达式 Python - 如何获取不连续的出现次数?
- ios - 缩放滚动视图内的内容视图不起作用
- post - 如何从struts自定义拦截器中的POST请求中获取请求有效负载?
- typescript - 生成联合字符串类型
- javascript - 在 javascript 中加载本地文本文件
- c++ - G++ 链接 - 仅链接使用的符号
- sql - 下一个工作日不是 sql 中的假期