简体   繁体   中英

Passing object attributes to its methods (Python)

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM