Python键入:基于另一个var定义类Var的类型
是否可以根据另一个字段定义Python类字段的类型? 这样的事情:
from dataclasses import dataclass
from typing import ClassVar
@dataclass
class A:
a: str
@dataclass
class B(A):
b: str
@dataclass
class UseA:
field_cls: ClassVar[type] = A
field: A # <-- here should be something other, not just "A"
class UseB(UseA):
field_cls = B
def print_b(self) -> None:
print(self.field.b) # Here mypy says that "A has no attribute b"
如果我将在此代码上运行 mypy -strict ,我将获得错误:“ A”没有属性“ b”
。
我需要通过另一个字段“ field_cls”动态定义“字段”的类型,因此键入诸如mypy和我的IDE(vscode)之类的检查器必须了解正确的类型 usebefiel.field.field.field
Is it possible to define type of the python class field based on another field?
Something like this:
from dataclasses import dataclass
from typing import ClassVar
@dataclass
class A:
a: str
@dataclass
class B(A):
b: str
@dataclass
class UseA:
field_cls: ClassVar[type] = A
field: A # <-- here should be something other, not just "A"
class UseB(UseA):
field_cls = B
def print_b(self) -> None:
print(self.field.b) # Here mypy says that "A has no attribute b"
If I'll run mypy --strict on this code I'll get the error: "A" has no attribute "b"
.
I need to define the type of "field" dynamically by another field "field_cls" so type checkers like mypy and my IDE (vscode) have to understand the right type of the UseB.field
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论