概要
Pythonで「引数にデフォルト値を設定する」の動作を確認してみました。以下のページを参考にしました。
実装
以下のファイルを作成しました。
sample.py
def myfunc(num1 = 10, str1 = "未入力", str2 = "不明"):
print("年齢は" + str(num1) + "です。", end='')
print("名前は" + str1 + "です。", end='')
print("住所は" + str2 + "です。")
myfunc(28, "Suzuki", "Tokyo")
myfunc(25, "Yamada")
myfunc(30)
myfunc()
def myfunc(str1, list1 = None):
if list1 is None:
list1 = ["a"]
list1.append(str1)
return list1
print(myfunc("b"))
print(myfunc("c"))
print(myfunc("d"))
以下のコマンドを実行しました。
$ python3 sample.py
年齢は28です。名前はSuzukiです。住所はTokyoです。
年齢は25です。名前はYamadaです。住所は不明です。
年齢は30です。名前は未入力です。住所は不明です。
年齢は10です。名前は未入力です。住所は不明です。
['a', 'b']
['a', 'c']
['a', 'd']
まとめ
何かの役に立てばと。