pythonclass

How to Set Default Argument of Class Method Equal to Class Attribute?


I have a class like:

class Cheetah:
    def __init__(self):
        self.speed = 20
    def move(self, speed):
        ....

How can I set the default value of speed in the method move to self.speed?

I've tried speed = self.speed, but I get a syntax error.


Solution

  • You can't, but there is no reason to. Default it to None and then just check within the method:

    def move(self, speed=None):
        if speed is None:
            speed = self.speed