0

Actually , I want to write

def w_cell(self, r, c, val, style=XLS.get_cell_stlye(self))

But it cannot, and show me the error

NameError: name 'self' is not defined

How could I set the default style in parameter rather than in function.

Thanks

class XLS():

    def get_cell_stlye(self):        
        return xlwt.easyxf("alignment: horizontal center,\
         vertical center, wrap true ;")


class TestCGI(object, XLS):
    def w_cell(self, r, c, val, style='null'):
            if style == 'null':
                style=XLS.get_cell_stlye(self)
            self.sht.write(r, c, val, style)
newBike
  • 14,385
  • 29
  • 109
  • 192

2 Answers2

0

The short answer is that you can't write that. Default arguments are evaluated when the function is created. At the function creation time, self doesn't exist yet1, so it can't have anything to do with the calculation of the default value.

1after all, if the class doesn't exist yet, it can't have any instances -- and even if it did, which instance would it pick to be self?

mgilson
  • 300,191
  • 65
  • 633
  • 696
0

Setting it in the function itself is fine, although you probably want to do it like this:

class TestCGI(object, XLS):
    def w_cell(self, r, c, val, style=None):
        if style is not None:
            style=XLS.get_cell_stlye(self)
        self.sht.write(r, c, val, style)
cjfro
  • 224
  • 1
  • 7
  • In this case, I would is `if style is not None` -- Your version would also pick up `style=0` which may or may not be meaningful. – mgilson Sep 27 '13 at 03:58