使用 openpyxl 对象初始化 python 数据类

Initialize python dataclass with an openpyxl object

我有 python class 这是一个用 openpyxl Cell 对象初始化的。它是一个传统的单元格class,它接受Cell对象并读取Cell对象的一些属性并将其存储为自己的,

import openpyxl as oxl
class oxl_cell_objectclass(object):
    def __init__(self, cell):
        self.cell = cell
        self.xl_column = cell.column
        self.xl_row = cell.row
        self.cell_value = cell.value

我如何在 python 数据 class 中做瘦身(在 python 3.7 + 中引入)。我尝试了下面显示的代码,它给了我一个异常,即找不到单元格,

@dataclass
class oxl_cell_dataclass:
    cell : oxl.cell.cell.Cell #openpyxl Cell object
    xl_column : oxl.cell.cell.Cell.column = cell.column #default value for xl_column attribute

我使用继承解决了这个问题。我必须对我的代码进行两处更改才能使其正常工作

  • 继承openpyxl Cell对象使代码工作
  • 定义一个post_init函数来分配单元格属性

工作代码如下所示,

@dataclass
class oxl_cell_dataclass(oxl.cell.cell.Cel):
    cell : oxl.cell.cell.Cell #openpyxl Cell object

    def __post_init__(self):
       self.xl_column = self.cell.column