目標
我正在嘗試撰寫一個函式,其中一個或多個輸入引數是由函式更新的全域變數,而不必return從函式內部獲取值。我知道我可以只從函式回傳一個元組或兩個單獨的值,但我認為如果可能的話,從函式內部更新全域變數將是另一種有趣的方法。
這樣做的原因
當全域變數已知(即之前在 python 腳本中定義)時,使用函式更新全域變數很容易。但是,我想在單獨的 .py 檔案中定義該函式,以便在其他 python 腳本中輕松使用該函式。因此,我需要能夠支持不同的變數名來更新。
雖然這完全沒有必要,但我只是對這是否可能感興趣。
示例偽代碼
我在想這樣的事情:
def math_function(input_val, squared_result, cubed_result):
squared_result = input_val**2 #update the var input as the squared_result parameter
cubed_result = input_val**3 #update the var input as the cubed_result parameter
在這里您將輸入號碼input_val和然后全域變數squared_result,并cubed_result與結果的功能更新。然后理論上它會像這樣作業:
#Declare global variables
b = 0
c = 0
#then somewhere in the code, call the function
math_function(2, b, c)
#check the new values
print(b) #Output: b = 4
print(c) #Output: c = 8
這將允許我在不同的 python 腳本中使用該函式,而不必擔心回傳結果的順序。
uj5u.com熱心網友回復:
第一:我絕不提倡這一點。
您可以使用globals內置函式按名稱訪問全域變數:
def gtest(name,value):
globals()[name] = value
gtest('new_global','new_value')
print(new_global)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/398014.html
下一篇:R中的不等組卡方檢驗?
