Home > Software design >  Passing object attributes to its methods (Python)
Passing object attributes to its methods (Python)

Time:06-09

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?

CodePudding user response:

The reason you can't use self.color as a default parameter value is that the default is evaluated at the time the method is defined (not at the time that it's called), and at the time the method is defined, there is no self object yet.

Assuming that a valid color is always a truthy value, I would write this as:

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()
  • Related