我使用字段(init=False(禁用初始化self.ref。然后它是post中的一个值。以下代码引发AttributeError: 'Data' object has no attribute 'ref'
from dataclasses import dataclass, field
def make_list(): return [[0] for k in range(9)]
@dataclass
class Data:
rows: list
cols: list
blocks: list
ref: dict = field(init=False)
def __init__(self, slots=None):
self.rows = make_list()
self.cols = make_list()
self.blocks = make_list()
if slots:
for i in range(9):
for j in range(9):
self.cols[j][i] = self.rows[i][j] = slots[i][j]
def __post_init__(self):
print("post-init executed")
self.ref = {"rows": self.rows, "cols": self.cols, "blocks": self.blocks}
test = Data()
print(test)
我使用的是python 3.8。该代码在pycharm/jupyter中都进行了测试。(相同错误(
编辑:在更正了打字错误:__post__init__
到__post_init__
之后,我仍然收到错误。
感谢@wim和@juanpa.arrivilaga
删除__init__
将修复问题,并让__post_init__
再次运行。(正如wim
和juanpa.arrivillaga
所指出的(如果我写自己的__init__
,为什么还要写__post_init__
,我可以在那里写我想要的所有后处理。(行订单(
from dataclasses import dataclass, field
@dataclass
class Data:
rows: list
cols: list = field(init=False)
blocks: list = field(init=False)
ref: dict = field(init=False)
def __post_init__(self):
print("post initnn")
self.cols = [k*10 for k in self.rows] # code transform rows to cols
self.blocks = [k*20 for k in self.rows] # code transform rows to blocks
self.ref = {"rows": self.rows, "cols": self.cols, "blocks": self.blocks}
test = Data([1,2,3])
print(test)
此外,我可能想重新考虑使用常规类重写它,因为在这里使用dataclass只提供了一个常规类。