如何更改可选函数参数的默认值

How to change default value of optional function parameter

我需要将 a.py 处的全局变量 Sb.py 更改为 S,但它在 a.py 处的函数中用作默认值。

a.py

S = "string"


def f(s=S):
    print(s)
    print(S)

b.py

import a


def main():
    a.S = "another string"
    a.f()


if __name__ == "__main__":
    main()

python b.py 输出

string
another string

而不是预期的

another string
another string

如果我像这样在 b.py 中调用 a.f

a.f(a.S)

这按预期工作,但是有什么方法可以更改默认变量值吗?

简短的回答是:你不能。

原因是函数默认参数是在函数定义时创建的,默认值并不意味着要重新定义。变量名称只绑定到一个值,仅此而已,您不能将该名称重新绑定到另一个值。首先,让我们看一下全局范围内的变量:

# 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 returns一个newstr,使得ab引用不同的对象。

函数也是如此:

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