Python 简明教程

Python - Default Arguments

Python Default Arguments

Python 允许对 default value 进行 define a function ,将其分配给一个或更多形式参数。如果未向其传递值,Python 将为此类参数使用默认值。如果传递了任何值,则会以实际传递的值覆盖默认值。

Python allows to define a function with default value assigned to one or more formal arguments. Python uses the default value for such an argument if no value is passed to it. If any value is passed, the default value is overridden with the actual value passed.

Example of Default Arguments

以下示例展示了 Python 默认参数的用法。在此,对函数的第二个调用不会向“城市”参数传递值,因此将使用其默认值“海德拉巴”。

The following example shows use of Python default arguments. Here, the second call to the function will not pass value to "city" argument, hence its default value "Hyderabad" will be used.

# Function definition
def showinfo( name, city = "Hyderabad" ):
   "This prints a passed info into this function"
   print ("Name:", name)
   print ("City:", city)
   return

# Now call showinfo function
showinfo(name = "Ansh", city = "Delhi")
showinfo(name = "Shrey")

它将生成以下 output

It will produce the following output

Name: Ansh
City: Delhi
Name: Shrey
City: Hyderabad

Example: Calling Function Without Keyword Arguments

让我们看看另一个为函数参数分配默认值示例。percent() 函数有一个名为“最大分数”的默认参数,该参数设置为 200。因此,我们可以忽略在调用函数时第三个参数的值。

Let us look at another example that assigns default value to a function argument. The function percent() has a default argument named "maxmarks" which is set to 200. Hence, we can omit the value of third argument while calling the function.

# function definition
def percent(phy, maths, maxmarks=200):
   val = (phy + maths) * 100/maxmarks
   return val

phy = 60
maths = 70
# function calling with default argument
result = percent(phy, maths)
print ("percentage:", result)

phy = 40
maths = 46
result = percent(phy, maths, 100)
print ("percentage:", result)

执行此代码后,会生成以下输出 −

On executing, this code will produce the following output −

percentage: 65.0
percentage: 86.0

Mutable Objects as Default Argument

Python 在定义函数时对默认参数求值一次,而不是在每次调用该函数时。因此,如果您使用可变默认参数并在给定函数中修改它,则相同的值会在后续函数调用中被引用。

Python evaluates default arguments once when the function is defined, not each time the function is called. Therefore, If you use a mutable default argument and modify it within the given function, the same values are referenced in the subsequent function calls.

Example

下面的代码解释了如何在 Python 中将可变对象用作默认参数。

The code below explains how to use mutable objects as default argument in Python.

def fcn(nums, numericlist = []):
   numericlist.append(nums + 1)
   print(numericlist)

# function calls
fcn(66)
fcn(68)
fcn(70)

执行以上代码时,它将产生以下输出 -

On executing the above code, it will produce the following output −

[67]
[67, 69]
[67, 69, 71]