0

我试图在dataclass(y_set_maxy_set_min) 中声明两个变量。下面是我的代码:

from dataclasses import dataclass

@dataclass
class Ymax_ymin: #has to be object inside the brackets
    y_default_max: int #500
    y_default_min: int #0
    current: int
    recommended: int

    def __post_init__(self):
          self.y_set_max = max(y_default_max,current,recommended)
          self.y_set_min = min(y_default_min,current,recommended)

current = 800
recommended = 650

set_axis = Ymax_ymin(500,0,current,recommended)

print(set_axis.y_set_max)
print(set_axis.y_set_min)

这是抛出错误: NameError: name y_default_maxis not defined

如何修改我的dataclass代码以便返回两个打印语句?

4

2 回答 2

3

如果要访问实例的属性,则需要在调用中包含该实例。虽然dataclass定义向您隐藏了构造函数,其中y_default_max传入的 被读入self.y_default_max,但它仍然会发生,如果您想要实例属性,则需要包含self..

此外,如果您想dataclass根据其他人计算一个 ' 属性,您可以使用init=False它来声明它并仍然获得类型提示等:

from dataclasses import dataclass, field


@dataclass
class YmaxYmin:
    current: int
    recommended: int
    y_default_max: int = 500
    y_default_min: int = 0
    y_set_max: int = field(init=False)
    y_set_min: int = field(init=False)

    def __post_init__(self):
        self.y_set_max = max(self.y_default_max, self.current, self.recommended)
        self.y_set_min = min(self.y_default_min, self.current, self.recommended)

鉴于此类定义,您的初始语句将正常运行:

set_axis = YmaxYmin(current=500, recommended=0, y_default_max=800, y_default_min=650)

print(set_axis.y_set_max)  # prints 800
print(set_axis.y_set_min)  # prints 0
于 2019-04-24T06:27:41.407 回答
1

语法与类型提示和默认参数相同:

from dataclasses import dataclass

@dataclass
class Ymax_ymin: #has to be object inside the brackets
    current: int
    recommended: int
    y_default_max: int = 500
    y_default_min: int = 0

    def __post_init__(self):
        self.y_set_max = max(self.y_default_max, current, recommended)
        self.y_set_min = min(self.y_default_min, current, recommended)

current = 800
recommended = 650

set_axis = Ymax_ymin(500, 0, current, recommended)

print(set_axis.y_set_max)
print(set_axis.y_set_min)

请注意,默认参数必须放在最后。另外,你self__post_init__.

于 2019-04-23T03:50:33.890 回答