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