Python键入:基于另一个var定义类Var的类型

发布于 2025-02-11 10:50:43 字数 667 浏览 1 评论 0原文

是否可以根据另一个字段定义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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文