引数のデフォルト値の注意ポイント
- CASE 1 : 引数にデフォルト値が設定されている場合、関数の実行時に指定がなくても問題ない。下記のcase1では第2引数、第3引数は引数を渡さなくても実行される。
- CASE 2 : デフォルト値の評価は、関数を定義した時点で、定義を書いたスコープで行われる。
#CASE 1
def ask_ok(prompt, retries=4, reminder='Please try again!'):
while True:
ok = input(prompt)
if ok in ('y', 'ye', 'yes'): #okにタプル('y', 'ye', 'yes')の中の値が含むかどうかを判定
return True
if ok in ('n', 'no', 'nope'): #okタプル('n', 'no', 'nope')の中の値が含むかどうかを判定
return False
retries -= 1
if retries < 0:
raise ValueError('invalid user response')
print(reminder)
ask_ok('Do you really want to quit?') #case1
# ask_ok('Do you really want to quit?', 2) #case2
# ask_ok('Do you really want to quit?', reminder= 'Please input yes or not!') #case3
# ask_ok('Do you really want to quit?', 3, 'Come on, only yes or not!') #case4
# CASE 2
i = 5
i = 6
def f(arg=i):
print(arg)
i=7
f()
f(8)
CASE 1
Do you really want to quit?
Please try again!
Do you really want to quit?
Please try again!
Do you really want to quit?
Please try again!
Do you really want to quit?
Please try again!
Do you really want to quit?
Traceback (most recent call last):
File "/Users/masashi/PycharmProjects/PythonLarning/PythonLarning/O'REILLY/argument_default.py", line 13, in <module>
ask_ok('Do you really want to quit?')
File "/Users/masashi/PycharmProjects/PythonLarning/PythonLarning/O'REILLY/argument_default.py", line 10, in ask_ok
raise ValueError('invalid user response')
ValueError: invalid user response
CASE 2
6 #f() デフォルトの引数が使われた
8 #f(8) 引数に8が渡された場合は、8が優先