Skip to content Skip to sidebar Skip to footer

Using Self.* As Default Value For A Method

def save_file(self, outputfilename = self.image_filename): self.file.read(outputfilename) .... gives NameError: name 'self' is not defined in the first line. It seems tha

Solution 1:

Use a default of None and detect that.

defsave_file(self, outputfilename=None): 
    if outputfilename isNone:
        outputfilename = self.image_filename
    self.file.read(outputfilename)
    ....

Solution 2:

The documentation states:

Default parameter values are evaluated when the function definition is executed.

This explains why the instance cannot be referenced. As others have said, use None as your default and fix up the value at function execution time when the instance is available.

Solution 3:

defsave_file(self, outputfilename=None): 
    outputfilename = outputfilename or self.image_filename
    self.file.read(outputfilename)

or even

defsave_file(self, outputfilename=None):         
    self.file.read(outputfilename or self.image_filename)

This may be nothing with one variable, but if you have, let's say, 5, this makes code easier to read, in my opinion.

Solution 4:

defsave_file(self, outputfilename = None):
    ifnot outputfilename:
        outputfilename = self.image_filename 
    self.file.read(outputfilename)
    ....

Post a Comment for "Using Self.* As Default Value For A Method"