Understanding the differences between two seemingly similar function definitions in Python is crucial for avoiding unintended side effects and understanding Python’s handling of default arguments.
Function Definition 1
def f(a, L=None):
if L is None:
L = []
L.append(a)
return L
Function Definition 2
def f(a, L=[]):
L.append(a)
return L
What Happens and Behind the Scenes
Function Definition 1: def f(a, L=None)
English:
def f(a, L=None):
if L is None:
L = []
L.append(a)
return L
- What Happens: When the function
f
is called, it checks if the second argumentL
isNone
. IfL
isNone
, it initializesL
as an empty list. Then, it appends the value ofa
toL
and returnsL
. - Behind the Scenes: The use of
None
as the default value forL
ensures that a new empty list is created each time the function is called without providing a second argument. This avoids the common pitfall of mutable default arguments.
Chinese:
def f(a, L=None):
if L is None:
L = []
L.append(a)
return L
- 发生了什么: 当调用函数
f
时,它检查第二个参数L
是否为None
。如果L
为None
,它将L
初始化为一个空列表。然后,它将a
的值添加到L
并返回L
。 - 幕后: 使用
None
作为L
的默认值可以确保每次调用函数而不提供第二个参数时都会创建一个新的空列表。这避免了可变默认参数的常见陷阱。
Function Definition 2: def f(a, L=[])
English:
def f(a, L=[]):
L.append(a)
return L
- What Happens: When the function
f
is called, it appends the value ofa
toL
and returnsL
. IfL
is not provided, the default value[]
(an empty list) is used. - Behind the Scenes: The default value
[]
is created once when the function is defined, not each time the function is called. Therefore, if the function is called multiple times without providing a new list forL
, the same list is used and modified, leading to unexpected behavior.
Chinese:
def f(a, L=[]):
L.append(a)
return L
- 发生了什么: 当调用函数
f
时,它将a
的值添加到L
并返回L
。如果未提供L
,则使用默认值[]
(一个空列表)。 - 幕后: 默认值
[]
在函数定义时创建一次,而不是每次调用函数时创建。因此,如果多次调用函数而不提供新的L
列表,则会使用并修改同一个列表,导致意外行为。
Practical Examples
Function Definition 1: def f(a, L=None)
English:
print(f(1)) # Output: [1]
print(f(2)) # Output: [2]
print(f(3)) # Output: [3]
- Each call creates a new list.
Chinese:
print(f(1)) # 输出: [1]
print(f(2)) # 输出: [2]
print(f(3)) # 输出: [3]
- 每次调用都会创建一个新的列表。
Function Definition 2: def f(a, L=[])
English:
print(f(1)) # Output: [1]
print(f(2)) # Output: [1, 2]
print(f(3)) # Output: [1, 2, 3]
- Each call modifies the same list.
Chinese:
print(f(1)) # 输出: [1]
print(f(2)) # 输出: [1, 2]
print(f(3)) # 输出: [1, 2, 3]
- 每次调用都会修改同一个列表。
Conclusion
English:
The key difference lies in how Python handles default arguments. Using None
as a default value and initializing the list inside the function ensures that a new list is created each time the function is called. Using a mutable default argument like []
leads to the same list being used across multiple function calls, which can cause unexpected behavior.
Chinese:
关键区别在于 Python 如何处理默认参数。使用 None
作为默认值并在函数内部初始化列表可以确保每次调用函数时都会创建一个新列表。使用可变的默认参数(如 []
)会导致在多次函数调用中使用相同的列表,从而可能导致意外行为。
Leave a Reply