在函数中最好不要用可变类型当参数

函数中参数的运行
在Python中当函数被定义时,默认参数只会运算一次,
而不是每次被调用时都会重新运算。
你应该永远不要定义可变类型的默认参数。除非你知道在做什么

foo = ['hi']
print(foo)
# Output: ['hi']

bar = foo
bar += ['bye']
print(foo)
print(bar)
# Output: ['hi', 'bye']
'''
这个情况只是针对可变数据类型。
当你将一个变量赋值为另一个可变类型的变量时,
对这个数据的任意改动会同时反映到这两个变量上去。
新变量只不过是老变量的一个别名而已。
'''
def add_to(num, target=[]):
    target.append(num)
    return target

add_to(1)
# Output: [1]

add_to(2)
# Output: [1, 2]

add_to(3)
print(add_to(42)) # [1, 2, 3, 42]
print(add_to(42)) # [1, 2, 3, 42, 42]
# Output: [1, 2, 3]
'''
在Python中当函数被定义时,默认参数只会运算一次,
而不是每次被调用时都会重新运算。
你应该永远不要定义可变类型的默认参数,除非你知道你正在做什么
'''
def add_to(element, target=None):
    if target is None:
        target = []
    target.append(element)
    return target
# 现在每当你在调用这个函数不传入 target 参数的时候,一个新的列表会被创建
print(add_to(42)) # [42]
print(add_to(42)) # [42]

努力拼搏吧,不要害怕,不要去规划,不要迷茫。但你一定要在路上一直的走下去,尽管可能停滞不前,但也要走。
原文地址:https://www.cnblogs.com/wkhzwmr/p/15272815.html