Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: passing instance variable to class method

I am using xlsxwriter and I have created a class where I have created a workbook. Then I have added 2 worksheets to it. Now I have written a method that's writing data to one of the worksheets, but now I would like to use it on both worksheets. This is a simple example to explain the situation:

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)

Now I'd like to use the write_data method for both worksheets, so I thought I'd pass the worksheet as a parameter, but unfortunately it's not that simple, as I cannot pass the instance variable self.ws1 or self.ws2.

So the question is: how can I do that?

I came up with a very nasty solution, like this:

def write_data(self, data, title, instance = 'ws1'):
    if instance == 'ws1':
        instance = self.ws1
        lineCounter = self.ws1LineCount
    elif instance == 'ws2':
        instance = self.ws2
        lineCounter = self.ws2LineCount

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

but honestly I don't like it. Is there a proper way to do it, or is it like a completely unreasonable thing?

like image 381
toti08 Avatar asked Aug 06 '26 19:08

toti08


1 Answers

Instead of the if block, better use workbook.get_worksheet_by_name() method

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

EDIT: or you can use getattr() function, e.g.

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
like image 164
buran Avatar answered Aug 08 '26 10:08

buran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!