LoginSignup
0
0

More than 3 years have passed since last update.

【Udemy Python3入門+応用】 51. デフォルト引数で気をつけること

Posted at

※この記事はUdemyの
現役シリコンバレーエンジニアが教えるPython3入門+応用+アメリカのシリコンバレー流コードスタイル
の講座を受講した上での、自分用の授業ノートです。
講師の酒井潤さんから許可をいただいた上で公開しています。

■デフォルト引数で気をつけること

◆空のリストや辞書はデフォルト引数に使わない
list_augment
def test_func(x, l = []):
    l.append(x)
    return l

r = test_func(100)
print(r)

r = test_func(100)
print(r)
result
[100]
[100, 100]

毎回新しいリストを使う場面が多いが、
そんなときにデフォルト引数に空のリストを設定してしまうと、
1つのリストをずっと使い続けることになる。

◆毎回初期化するように組み込む
list_augment
def test_func(x, l = None):
    # lを空のリストに初期化する
    if l is None:
        l = []
    l.append(x)
    return l

r = test_func(100)
print(r)

r = test_func(100)
print(r)
result
[100]
[100]

def内で、最初にlを初期化するように記述してやる。
そうすると、test_funcを呼び出すごとに毎回lの初期化が行われるため、
毎回空のリストを使えるようになる。

0
0
0

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