顯然不可能將物件的屬性傳遞給它自己的方法:
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)
有沒有更好(更優雅?)的方法來做到這一點?
uj5u.com熱心網友回復:
您不能將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()
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/487433.html