简体   繁体   中英

understanding dataclass field usage

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.

From the documentation (emphasis mine):

The dataclass() decorator examines the class to find field s. 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.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM