了解数据级字段使用
我对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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
从文档(强调地雷)中:
因此,该类型提示主要用作标志来告诉
dataclass
以注意该名称。这两个例外是注释是
classVar
或initvar
,用于指示名称不是实例属性,而是class属性或init-horly commine cam分别。我认为的第三个例外是Python 3.10中引入的新
kw_only
值,这表明不能将以下字段作为位置参数传递到__ INT __ INT __ INT __
。 (因此,“字段”是这样的,根本没有定义字段,但它仍然是一个装饰的名称,其类型dataclass
待注意。)From the documentation (emphasis mine):
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
orInitVar
, 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 typedataclass
pays attention to.)