问题描述
我有一个用openpyxl Cell对象初始化的python类。它是传统的单元格类,它接受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数据类中进行精简(在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