def save_file(self, outputfilename = self.image_filename):
self.file.read(outputfilename)
....
在第一行中给出NameError: name 'self' is not defined
。似乎Python不接受它。如何重写代码以免引发异常?
答案 0 :(得分:34)
使用默认值None
并检测到。
def save_file(self, outputfilename=None):
if outputfilename is None:
outputfilename = self.image_filename
self.file.read(outputfilename)
....
答案 1 :(得分:13)
答案 2 :(得分:3)
def save_file(self, outputfilename = None):
if not outputfilename:
outputfilename = self.image_filename
self.file.read(outputfilename)
....
答案 3 :(得分:3)
def save_file(self, outputfilename=None):
outputfilename = outputfilename or self.image_filename
self.file.read(outputfilename)
甚至
def save_file(self, outputfilename=None):
self.file.read(outputfilename or self.image_filename)
对于一个变量,这可能不算什么,但是如果你有,那么就说5,这使得代码更易于阅读。