显然不可能将对象的属性传递给它自己的方法:
def drawBox(color):
print("A new box of color ", color)
return
class Box:
def __init__(self, color):
self.defaultColor = color
self.color = color
def update(self, color = self.defaultColor):
self.color = color
drawBox(color)
这行不通:
Traceback (most recent call last):
File "<string>", line 5, in <module>
File "<string>", line 9, in Box
NameError: name 'self' is not defined
我找到了一个绕过这个问题的方法,像这样:
def drawBox(color):
print("A new box of color ", color)
return
class Box:
def __init__(self, color):
self.defaultColor = color
self.color = color
def update(self, color = None):
if color == None:
self.color = self.defaultColor
else:
self.color = color
drawBox(color)
是否有更好的(更优雅的?)方法来做到这一点?
不能使用self.color
作为默认参数值的原因是默认值是在方法定义时计算的(而不是在调用时),并且在方法定义时还没有self
对象。
假设一个有效的color
总是一个真值,我将把它写成:
class Box:
def __init__(self, color):
self.default_color = self.color = color
def draw(self):
print(f"A new box of color {self.color}")
def update(self, color=None):
self.color = color or self.default_color
self.draw()