[英]How to change default value of optional function parameter
我需要從b.py
更改a.py
的全局變量S
,但它用作a.py
函數中的默認值。
一個.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
調用af
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
返回一個新的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"
定義。 這是無法改變的。 即使使用可變默認值,例如在這個問題中:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.