简体   繁体   English

属性的 Python 数据类后初始化

[英]Python dataclass post initialisation for attributes

In the documentation for a dataclass the following example is given when doing some additional calculations at the initialisation of the instance:dataclass的文档中,在实例初始化时进行一些额外计算时给出了以下示例:

@dataclass
class C:
    a: float
    b: float
    c: float = field(init=False)

    def __post_init__(self):
        self.c = self.a + self.b

In the example, the field function is called with init=False .在示例中,使用init=False调用field函数。 I'm wondering why this is required, because it doesn't seem to be needed.我想知道为什么需要这样做,因为它似乎不需要。 Have I missed something important?我错过了什么重要的事情吗?

For example, the following code also seems to work fine:例如,以下代码似乎也能正常工作:

@dataclass
class C:
    a: float
    b: float

    def __post_init__(self):
        self.c = self.a + self.b
        self.d = self.a**2 + self.b**2

Are there likely to be any problems caused by the second example where the attributes are not defined before __post_init__ is called?__post_init__之前__post_init__属性的第二个示例是否可能导致任何问题? I'm wondering because I'm doing something like the second example, but with many more attributes and with the addition that b is an InitVar , and I've not noticed any problems yet.我想知道,因为我正在做类似于第二个例子的事情,但是有更多的属性,并且b是一个InitVar ,我还没有注意到任何问题。

In this case在这种情况下

@dataclass
class C:
    a: float
    b: float

    def __post_init__(self):
        self.c = self.a + self.b
        self.d = self.a**2 + self.b**2

c and d are available in instance of C , but repr of said instance does not include that, for example: cdC实例中可用,但所述实例的repr不包括,例如:

somec = C(3.0,5.0)
print(somec)

output输出

C(a=3.0, b=5.0)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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