了解数据级字段使用

发布于 2025-02-10 04:49:14 字数 561 浏览 2 评论 0原文

我对Dataclasses中字段()的使用方式的使用方式感到困惑。 我有这个(毫无意义的)示例:

from dataclasses import dataclass, field

@dataclass
class Person:
    name: str = field(init=False)

    def print_name(self):
        print(self.name)


dieter = Person()
dieter.print_name()

我希望这会创建一个空字符串。但是,只有当我添加参数默认值=“”时才发生。 甚至在pycharm中,没有语法突出显示时,当我编写以下代码时:

name: int = field(init=False, default="")

如果没有语法突出显示,那么类型提示的点是什么? 我真的没有任何问题,我只是想掌握,实际上正在发生的事情。

使用情况是,我正在创建一个类,后来包含matplotlib轴,绘图等。由于它们在开始时不存在,所以我只想初始化它们,因此它们已连接到类,以后可以是创建。

I am confused about how the usage of field() in dataclasses works.
I have this (senseless) example:

from dataclasses import dataclass, field

@dataclass
class Person:
    name: str = field(init=False)

    def print_name(self):
        print(self.name)


dieter = Person()
dieter.print_name()

I would expect this to create an empty string. However, this only happens, when I add the parameter default="".
Evenmore, in pycharm, no syntax highlight complains, when I write following code:

name: int = field(init=False, default="")

What is the point of type hints, if there is not syntax highlighting?
I don't really have any problem, I'm just trying to grasp, what is actually happening.

The usage case is, that I am creating a class, that later contains matplotlib axes, plots etc. Since they don't exist in the beginning, I only want to initialize them, so they are connected to the class, and can later be created.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

失与倦" 2025-02-17 04:49:14

从文档(强调地雷)中:

dataclass()装饰器检查类以查找字段 s。 字段定义为具有类型注释的类变量。如下所述两个例外, dataClass()在变量注释中指定的类型

因此,该类型提示主要用作标志来告诉dataclass以注意该名称。

这两个例外是注释是classVarinitvar,用于指示名称不是实例属性,而是class属性或init-horly commine cam分别。

我认为的第三个例外是Python 3.10中引入的新kw_only值,这表明不能将以下字段作为位置参数传递到__ INT __ INT __ INT __。 (因此,“字段”是这样的,根本没有定义字段,但它仍然是一个装饰的名称,其类型dataclass待注意。)

From the documentation (emphasis mine):

The dataclass() decorator examines the class to find fields. A field is defined as a class variable that has a type annotation. With two exceptions described below, nothing in dataclass() examines the type specified in the variable annotation.

So the type hint is mainly used as a flag to tell dataclass to pay attention to the name.

The two exceptions are if the annotation is ClassVar or InitVar, used to indicate that the name is not an instance attribute, but either a class attribute or an init-only parameter, respectively.

What I consider a third exception is the new KW_ONLY value introduced in Python 3.10, which indicates that the following fields cannot be passed as positional arguments to __init__. (The "field" so annotated doesn't define a field at all, but it's still a decorated name whose type dataclass pays attention to.)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文