本文介绍了使用 self.* 作为方法的默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

给出 NameError: name 'self' is not defined 在第一行.似乎Python不接受它.如何重写代码使其不引发异常?

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?

推荐答案

使用默认值 None 并检测.

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)
    ....

这篇关于使用 self.* 作为方法的默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 02:29