是否可以使用Python的受约束类型Var使子类不兼容?
根据 docs> docs ,受约束的 > typevar
s应该完全匹配。
但是,当使用自定义类时,该行为似乎是违反直觉的:
from dataclasses import dataclass
from typing import Generic, TypeVar
@dataclass
class PrinterConnection:
name: str = ""
@dataclass
class WiFiPrinterConnection(PrinterConnection):
name = "WiFi"
@dataclass
class USBPrinterConnection(PrinterConnection):
name = "USB"
@dataclass
class USBTypeCPrinterConnection(USBPrinterConnection):
name = "USB-C"
Connection = TypeVar("Connection", USBPrinterConnection, WiFiPrinterConnection)
@dataclass
class Printer(Generic[Connection]):
connection: Connection
Printer(WiFiPrinterConnection()) # No Warning - As Expected
Printer(USBPrinterConnection()) # No Warning - As Expected
Printer(USBTypeCPrinterConnection()) # No Warning - NOT Expected
在此示例中, usbtypecprinternection
不是 typevar
>中定义的类型之一,但没有发出警告。
我的问题是:
- 为什么在这里没有警告?
- 有没有办法允许特定的类而不是其子类?
这些示例是用Python 3.10完成的,用于检查类型。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
受约束的
typeVar
必须解决指定类型之一,并且子类可以解散给其父母。考虑
;
child
类型var 已解决parent> parent
。A constrained
TypeVar
must resolve to one of the specified types, and a subclass can resolve to its parent.consider
Playground
as you can see even tho we passed a
Child
the type var was resolved to aParent
.