2

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

4

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
  • 567,968
  • 59
  • 825
  • 842
  • 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
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
  • 71
  • 4