开发者

Using self.* as default value for a method [duplicate]

This question already has answers here: How can I avoid issues caused by Python's early-bound default parameters (e.g. mutable default arguments "remembering" old data)? (10 answers) Closed 5 years ago.
def s开发者_StackOverflow社区ave_file(self, outputfilename = self.image_filename): 
    self.file.read(outputfilename)
    ....

gives NameError: name 'self' is not defined in the first line. It seems that Python doesn't accept it. How can I rewrite the code so it doesn't raise an exception?


Use a default of None and detect that.

def save_file(self, outputfilename=None): 
    if outputfilename is None:
        outputfilename = self.image_filename
    self.file.read(outputfilename)
    ....


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.


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

or even

def save_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.


def save_file(self, outputfilename = None):
    if not outputfilename:
        outputfilename = self.image_filename 
    self.file.read(outputfilename)
    ....
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜