Python のデフォルト引数

Python では、関数の引数にデフォルト値を設定できます。関数が引数なしで呼び出された場合、引数はデフォルト値を取得します。

デフォルトの引数:

Python には、関数の引数の構文とデフォルト値を表す別の方法があります。デフォルト値は、関数呼び出し中に引数の値が渡されない場合、関数の引数がその値を取ることを示します。デフォルト値は、次の形式の assign(=) 演算子を使用して割り当てられます。 キーワード名 =値。
これを関数で理解してみましょう 学生 。関数 学生 3 つの引数が含まれており、そのうち 2 つの引数にはデフォルト値が割り当てられます。したがって、関数は 学生 必須の引数を 1 つ受け入れます ( ファーストネーム )、残りの 2 つの引数はオプションです。

Python3




def> student(firstname, lastname> => 'Mark'> , standard> => 'Fifth'> ):> > print> (firstname, lastname,> 'studies in'> , standard,> 'Standard'> )>


関数を呼び出すときは、次の点に留意する必要があります。

  1. キーワード引数を渡す場合、引数の順序が重要です。
  2. 1 つのパラメーターに対して値は 1 つだけである必要があります。
  3. 渡されたキーワード名は、実際のキーワード名と一致する必要があります。
  4. キーワード以外の引数を含む関数を呼び出す場合、順序が重要です。

例 #1: キーワード引数なしで関数を呼び出す

Python3




def> student(firstname, lastname> => 'Mark'> , standard> => 'Fifth'> ):> > print> (firstname, lastname,> 'studies in'> , standard,> 'Standard'> )> # 1 positional argument> student(> 'John'> )> # 3 positional arguments> student(> 'John'> ,> 'Gates'> ,> 'Seventh'> )> # 2 positional arguments> student(> 'John'> ,> 'Gates'> )> student(> 'John'> ,> 'Seventh'> )>

出力:

John Mark studies in Fifth Standard John Gates studies in Seventh Standard John Gates studies in Fifth Standard John Seventh studies in Fifth Standard 

最初の呼び出しでは、必須の引数は 1 つだけで、残りの引数はデフォルト値を使用します。 2回目の電話では、 苗字 標準引数の値はデフォルト値から新しい渡された値に置き換えられます。関数の 2 回目、3 回目、4 回目の呼び出しから、引数の順序が重要であることがわかります。

例 #2: キーワード引数を使用した関数の呼び出し

Python3




def> student(firstname, lastname> => 'Mark'> , standard> => 'Fifth'> ):> > print> (firstname, lastname,> 'studies in'> , standard,> 'Standard'> )> # 1 keyword argument> student(firstname> => 'John'> )> # 2 keyword arguments> student(firstname> => 'John'> , standard> => 'Seventh'> )> # 2 keyword arguments> student(lastname> => 'Gates'> , firstname> => 'John'> )>

出力:

John Mark studies in Fifth Standard John Mark studies in Seventh Standard John Gates studies in Fifth Standard 

最初の呼び出しでは、必須のキーワード引数は 1 つだけです。 2 番目の呼び出しでは、1 つは必須の引数、もう 1 つはオプション (標準) で、その値はデフォルトから新しい渡し値に置き換えられます。 3 回目の呼び出しでは、キーワード引数の順序は重要ではないことがわかります。

例 #3: 一部の無効な関数呼び出し

Python3




def> student(firstname, lastname> => 'Mark'> , standard> => 'Fifth'> ):> > print> (firstname, lastname,> 'studies in'> , standard,> 'Standard'> )> # required argument missing> student()> # non keyword argument after a keyword argument> student(firstname> => 'John'> ,> 'Seventh'> )> # unknown keyword argument> student(subject> => 'Maths'> )>

上記のコードは、次の理由によりエラーをスローします。

  • 最初の呼び出しでは、パラメータに値が渡されません ファーストネーム これは必須パラメータです。
  • 2 番目の呼び出しでは、キーワード引数の後にキーワード以外の引数があります。
  • 3 回目の呼び出しでは、渡されたキーワード引数が実際のキーワード名の引数と一致しません。

Python で可変オブジェクトをデフォルトの引数値として使用する

これは非常に慎重に行う必要があります。その理由は、引数のデフォルト値は、コントロールが関数に到達したときに 1 回だけ評価されるためです。

初めての定義。その後、同じ値 (または変更可能なオブジェクト) が後続の関数呼び出しで参照されます。
例を見てみると、より明確になります

Python3




# mutable default argument values example using python list> # itemName is the name of the item that we want to add to list> # that is being passed, or if it is not passed then appending in> # the default list> def> appendItem(itemName, itemList> => []):> > itemList.append(itemName)> > return> itemList> print> (appendItem(> 'notebook'> ))> print> (appendItem(> 'pencil'> ))> print> (appendItem(> 'eraser'> ))>

出力

['notebook'] ['notebook', 'pencil'] ['notebook', 'pencil', 'eraser'] 

リストを渡さない場合、各関数呼び出しで新しいリストが作成されると仮定した場合に期待されること

['ノート']

['鉛筆']

['消しゴム']

しかし、プログラムの実際の出力を見ればわかるように、関数が呼び出されるたびに同じリストが使用され、新しい呼び出しで新しいリストは作成されません。

辞書を使った例

Python3




# mutable default argument values example using python dictionary> # itemName is the name of item and quantity is the number of such> # items are there> def> addItemToDictionary(itemName, quantity, itemList> => {}):> > itemList[itemName]> => quantity> > return> itemList> print> (addItemToDictionary(> 'notebook'> ,> 4> ))> print> (addItemToDictionary(> 'pencil'> ,> 1> ))> print> (addItemToDictionary(> 'eraser'> ,> 1> ))>

出力

{'notebook': 4} {'notebook': 4, 'pencil': 1} {'notebook': 4, 'pencil': 1, 'eraser': 1} 

関数呼び出しごとに新しい辞書が作成されると仮定した場合に期待されること

{「ノートブック」: 4}

{「鉛筆」: 1}

{「消しゴム」: 1}

しかし、プログラムの実際の出力は明らかに異なり、後続の各呼び出しで同じ辞書が使用されていることを示していることがわかります。

ここで重要なのは、そのようなシナリオは避けるべきだということです。

ベストプラクティス

デフォルト値を none として割り当て、予期されるリストまたはディクショナリの引数が none であるかどうかを関数でチェックインします。

なしの場合は、要件に応じてリストまたは辞書を割り当てます。

Python3




# using None as values of the default arguments> print> (> '#list'> )> def> appendItem(itemName, itemList> => None> ):> > if> itemList> => => None> :> > itemList> => []> > itemList.append(itemName)> > return> itemList> print> (appendItem(> 'notebook'> ))> print> (appendItem(> 'pencil'> ))> print> (appendItem(> 'eraser'> ))> # using None as value of default parameter> print> (> ' #dictionary'> )> def> addItemToDictionary(itemName, quantity, itemList> => None> ):> > if> itemList> => => None> :> > itemList> => {}> > itemList[itemName]> => quantity> > return> itemList> print> (addItemToDictionary(> 'notebook'> ,> 4> ))> print> (addItemToDictionary(> 'pencil'> ,> 1> ))> print> (addItemToDictionary(> 'eraser'> ,> 1> ))>

出力

#list ['notebook'] ['pencil'] ['eraser'] #dictionary {'notebook': 4} {'pencil': 1} {'eraser': 1} 

ここでは、関数が呼び出され、リストまたは辞書が引数として関数に渡されないたびに、新しいリストまたは辞書が作成されることがはっきりとわかります。