LoginSignup
49
21

More than 5 years have passed since last update.

Pythonの関数の引数にデフォルト値を含む時の引数の順序

Last updated at Posted at 2017-10-19

Pythonで関数を定義する時に、default値を与えることがしばしばあると思います。

以下のように仮に引数a,bを引き取ってその和を返す関数を考えることにします。

Python
def hoge(a,b):
    return a + b

この時引数aのdefault値をa=1としたいと考えて以下のように関数を定義します。

Python
def hoge(a=1,b):
    return a + b

すると

Error
SyntaxError: non-default argument follows default argument

とデフォルト値を取らない引数がデフォルト値を取る引数の後になってるよとお叱りを受けます。
そこで以下のように引数の順序をお叱りの通り直すとちゃんと定義できます。

Python
def hoge(b,a=1):
    return a + b

ただそれだけの話です。
(おそらく処理系の話的なものだと思うけれど、実際のところどうなのだろう?)

49
21
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
49
21