简短的回答是:你不能。
这样做的原因是函数默认参数是在函数定义时创建的,而默认值并不意味着要重新定义。变量名称绑定到一个值一次,仅此而已,您不能将该名称重新绑定到另一个值。首先,让我们看一下全局范围内的变量:
# create a string in global scope
a = "string"
# b is "string"
b = a
a += " new" # b is still "string", a is a new object since strings are immutable
您现在刚刚将一个新名称绑定到“string”,而“string new”是绑定到 a 的全新值,它不会更改 b,因为 str += str 返回一个 new str,使得a和b指向不同的对象。
函数也是如此:
x = "123"
# this expression is compiled here at definition time
def a(f=x):
print(f)
x = "222"
a()
# 123
变量f 在定义时使用默认值"123" 定义。这是无法改变的。即使有可变的默认值,例如this 问题:
x = []
def a(f=x):
print(x)
a()
[]
# mutate the reference to the default defined in the function
x.append(1)
a()
[1]
x
[1]
默认参数已定义,名称f 绑定到值[],无法更改。您可以更改与f 关联的值,但不能将f 绑定到默认值。进一步说明:
x = []
def a(f=x):
f.append(1)
print(f)
a()
x
[1]
# re-defining x simply binds a new value to the name x
x = [1,2,3]
# the default is still the same value that it was when you defined the
# function, albeit, a mutable one
a()
[1, 1]
A) 将全局变量作为参数传递给函数或 B) 将全局变量用作 global 可能会更好。如果你要改变你想使用的全局变量,不要把它设置为默认参数,选择一个更合适的默认值:
# some global value
x = "some default"
# I'm choosing a default of None here
# so I can either explicitly pass something or
# check against the None singleton
def a(f=None):
f = f if f is not None else x
print(f)
a()
some default
x = "other default"
a()
other default
a('non default')
non default