4

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.

4
  • why do you want to do this? Commented Jan 18, 2018 at 15:40
  • Just so if I call cheetah.move() and don't pass in a speed parameter, it will default to 20. Commented Jan 18, 2018 at 15:41
  • Does this answer your question? Can I use a class attribute as a default value for an instance method? Commented May 17, 2022 at 9:49
  • Isnt it an instance attribute ??? Class attributes goes before init , doesnt it ? Commented Dec 23, 2024 at 20:51

2 Answers 2

8

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
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks Daniel. I thought there might have been a quick trick to do this without the need for an if statement, but apparently not!
Well, you could do it do_move_logic(speed or self.speed) for example, but that's not as clear.
The default for the speed argument is set before any instances of Cheetah are defined; you have to do it this way.
@Jack What chepner said. Default args are evaluated once, when the function / method is created, not each time it's called.
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] `
1

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
        ....

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.