Python:将实例变量传递给类方法

时间:2018-12-06 12:22:51

标签: python python-2.7 xlsxwriter

我正在使用xlsxwriter,并且在创建工作簿的位置创建了一个类。然后,我向其中添加了2个工作表。 现在,我已经编写了一种将数据写入其中一个工作表的方法,但是现在我想在两个工作表中都使用它。这是一个解释这种情况的简单示例:

import xlsxwriter

class ExcelWorkbook():
    def __init__(self, filename):
        self.wb = xlsxwriter.Workbook(filename)
        self.ws1 = self.wb.add_worksheet('Num')
        self.ws1LineCount = 0
        self.ws2 = self.wb.add_worksheet('Result')
        self.ws2LineCount = 0

    def write_data(self, data, title):        
        self.ws1.write_row(self.ws1LineCount, 0, title)
        self.ws1LineCount += 1
        self.ws1.write_row(self.ws1LineCount, 0, data)
        self.ws1LineCount += 1

xlsxWorkbook = ExcelWorkbook('Test2.xlsx')
numArr = (0.000000520593523979187, 13.123456789, 1.789456, 0.002345, 0.00123, 1)
titleBar = ('Date', 'quantity', 'Average [m]', 'Standard Dev [m]', 'Test', 'Success')
xlsxWorkbook.write_data(numArr, titleBar)

现在,我想在两个工作表中都使用write_data方法,所以我认为我会将工作表作为参数传递,但是不幸的是,它不是那么简单,因为我无法传递实例变量{{ 1}}或self.ws1

问题是:我该怎么做?

我想出了一个非常讨厌的解决方案,例如:

self.ws2

但是老实说我不喜欢它。有适当的方法可以做到吗,还是完全不合理?

4 个答案:

答案 0 :(得分:2)

最好使用workbook.get_worksheet_by_name()方法来代替if块

def write_data(self, data, title, ws = 'Num'):
    wsheet = self.wb.get_worksheet_by_name(ws)
    wsheet.write_row(self.ws1LineCount, 0, title)
    lineCounter += 1
    wsheet.write_row(self.ws1LineCount, 0, data)
    lineCounter += 1

编辑:或者您可以使用getattr()函数,例如

def write_data(self, data, title, ws = 'ws1'):
    wsheet = getattr(self, ws, self.ws1))
    wsheet.write_row(self.ws1LineCount, 0, title)
    lineCounter += 1
    wsheet.write_row(self.ws1LineCount, 0, data)
    lineCounter += 1

答案 1 :(得分:1)

我会做这样的事情:

from collections import defaultdict
import xlsxwriter

class ExcelWorkbook():
    def __init__(self, filename):
        self.wb = xlsxwriter.Workbook(filename)

        self.ws1 = self.wb.add_worksheet('Num')
        self.ws2 = self.wb.add_worksheet('Result')
        self._line_counts = defaultdict(int)

    def write_data(self, ws, data, title):
        self._write_row(ws, title)
        self._write_row(ws, data)

    def _write_row(self, ws, content):
        ws.write_row(self._line_counts[ws], 0, content)
        self._line_counts[ws] += 1

xlsxWorkbook = ExcelWorkbook('Test2.xlsx')
numArr = (0.000000520593523979187, 13.123456789, 1.789456, 0.002345, 0.00123, 1)
titleBar = ('Date', 'quantity', 'Average [m]', 'Standard Dev [m]', 'Test', 'Success')
xlsxWorkbook.write_data(xlsxWorkbook.ws1, numArr, titleBar)
xlsxWorkbook.write_data(xlsxWorkbook.ws2, numArr, titleBar)

通过使用defaultdict,您无需为每个工作表显式保留行数变量。 write_data函数接受一个新参数ws,以便您可以设置应写入的工作表。可以将写一行分解为一个单独的方法,以减少代码重复。

这能回答您的问题吗?

编辑:

默认值无法访问self,但是您可以轻松解决此问题:

def write_data(self, data, title, ws=None):
        if ws is None:            
            ws = self.ws1
        self._write_row(ws, title)
        self._write_row(ws, data)

答案 2 :(得分:1)

也许您应该考虑拥有一个额外的类ExcelWorksheet,以便将与它们相关的所有逻辑放入其中:

class ExcelWorksheet(object):
    def __init__(self, workbook, name):
        self.wb = workbook
        self.ws = self.wb.add_worksheet(name)
        self.wsLineCount = 0

    def write_data(self, data, title):        
        self.ws.write_row(self.wsLineCount, 0, title)
        self.wsLineCount += 1
        self.ws.write_row(self.wsLineCount, 0, data)
        self.wsLineCount += 1

这样,您可以将代码重构为:

class ExcelWorkbook(object):
    def __init__(self, filename):
        self.wb = xlsxwriter.Workbook(filename)
        self.ws1 = ExcelWorksheet(self.wb, 'Num')
        self.ws2 = ExcelWorksheet(self.wb, 'Result')


xlsxWorkbook = ExcelWorkbook('Test2.xlsx')
numArr = (0.000000520593523979187, 13.123456789, 1.789456, 0.002345, 0.00123, 1)
titleBar = ('Date', 'quantity', 'Average [m]', 'Standard Dev [m]', 'Test', 'Success')
xlsxWorkbook.ws1.write_data(numArr, titleBar)
xlsxWorkbook.ws2.write_data(numArr, titleBar)

答案 3 :(得分:-1)

使用vars(self),您可以作为字典访问对象的任何元素。

然后vars(self)[“ ws1”]就像self.ws1,而vars(self)[“ ws2”]就像self.ws2

然后,您只需要在write_data中传递键参数“ ws1”或“ ws2”即可。

def write_data(self, data, title, key='ws1'):
    instance = vars(self)[key]
    lineCounter = vars(self)[key+"LineCount"]

    instance.write_row(lineCounter , 0, title)
    lineCounter += 1
    instance.write_row(lineCounter , 0, data)
    lineCounter += 1