3

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.

Thanks,

Jack

  • why do you want to do this? – Julian Rachman Jan 18 '18 at 15:40
  • Just so if I call `cheetah.move()` and don't pass in a `speed` parameter, it will default to `20`. –  Jan 18 '18 at 15:41
  • Does this answer your question? [Can I use a class attribute as a default value for an instance method?](https://stackoverflow.com/questions/4041624/can-i-use-a-class-attribute-as-a-default-value-for-an-instance-method) – LondonRob May 17 '22 at 09:49

2 Answers2

5

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
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
  • Thanks Daniel. I thought there might have been a quick trick to do this without the need for an `if` statement, but apparently not! –  Jan 18 '18 at 15:45
  • 1
    Well, you could do it `do_move_logic(speed or self.speed)` for example, but that's not as clear. – Daniel Roseman Jan 18 '18 at 15:46
  • 2
    The default for the `speed` argument is set before any instances of `Cheetah` are defined; you *have* to do it this way. – chepner Jan 18 '18 at 15:50
  • 1
    @Jack What chepner said. Default args are evaluated once, when the function / method is created, not each time it's called. – PM 2Ring Jan 18 '18 at 15:53
  • Sorry for bringing up this old question. Is there a way to do this smoothly for a variable number of arguments? e.g. (doesn't work) ` def play(self, arg1=None, arg2=None): for arg in locals(): if locals()[arg] is None: locals()[arg] = self.__dict__[arg] ` – Annie Jul 29 '22 at 05:22
0

One possible way is to

class Cheetah:
    def __init__(self):
        self.speed = 20
    def move(self, speed=None):
        if speed is None:
           speed = self.speed
        ....
ZYYYY
  • 81
  • 4