Python | 默認參數 (Python | default parameters)
A default parameter is a value provided in a function declaration that is automatically assigned by the compiler if the caller of the function doesn't provide a value for the parameter with the default value.
默認參數是函數聲明中提供的值,如果函數的調用者不提供默認值的參數值,則編譯器自動為其賦值 。
Following is a simple Python example to demonstrate the use of default parameters. We don't have to write 3 Multiply functions, only one function works by using default values for 3rd and 4th parameters.
以下是一個簡單的Python示例,以演示默認參數的用法 。 我們沒有使用默認值3 和 第 4點的參數寫3個乘功能,只有一種功能的作品。
Code:
碼:
# A function with default arguments, it can be called with
# 2 arguments or 3 arguments or 4 arguments .
def Multiply( num1, num2, num3 = 5, num4 = 10 ):
return num1 * num2 * num3 * num4
# Main code
print(Multiply(2,3))
print(Multiply(2,3,4))
print(Multiply(2,3,4,6))
Output
輸出量
300
240
144
Key points:
關鍵點:
1) Default parameters are different from constant parameters as constant parameters can't be changed whereas default parameters can be overwritten if required.
1) 默認參數與常量參數不同,因為不能更改常量參數,而如果需要可以覆蓋默認參數 。
2) Default parameters are overwritten when the calling function provides values for them. For example, calling of function Multiply(2, 3, 4, 6) overwrites the value of num3 and num4 to 4 and 6 respectively.
2)調用函數為其提供默認值時, 默認參數將被覆蓋。 例如,調用函數Multiply( 2,3,4,6 ) 會將num3和num4的值分別覆蓋為4和6 。
3) During calling of function, arguments from calling a function to parameters of the called function are copied from left to right. Therefore, Multiply(2, 3, 4) will assign 2, 3 and 4 to num1, num2, and num3. Therefore, the default value is used for num4 only.
3)在調用函數期間,從調用函數到被調用函數的參數的參數從左到右復制。 因此, 乘(2,3,4)將分配2,3和4至NUM1,NUM2和NUM3。 因此,默認值僅用于num4 。
翻譯自: https://www.includehelp.com/python/default-parameters.aspx