It is apparently impossible to pass attributes of an object to its own methods:
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)
This does not work:
Traceback (most recent call last):
File "<string>", line 5, in <module>
File "<string>", line 9, in Box
NameError: name 'self' is not defined
I found a way to bypass this issue like this:
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)
Is there a better (more elegant?) way to do this?
selfis not defined in the class body -- of course not,selfis simply the conventional name given to the first paramter of a method, it won't be defined until you call the methodif color is None: ...to be more idiomaticdef update(self, color = self.defaultColor):is not passing anything, that is part of a function definition. There is no "passing" involved because it isn't a function call