我正在嘗試在 exec 字串中宣告和更改全域變數,如下所示:
ostr = "didn't work"
nstr = "worked"
def function():
exec("global ostr; ostr = nstr")
#global ostr; ostr = nstr
print(ostr)
lv='ostr' in globals()
print(lv)
ostr='asd'
function()
但是,這在列印陳述句中出錯:
UnboundLocalError: local variable 'ostr' referenced before assignment
但是,如果我在 exec 陳述句之后注釋掉“exec”行和取消注釋行,代碼就可以正常作業。
如何使用“exec”修復此錯誤?我想宣告全域變數并修改 exec 字串中的這些全域變數,并使這些修改在后續行的“函式”中可見。
uj5u.com熱心網友回復:
您必須宣告您在函式中使用全域 ostr 才能列印它。這段代碼輸出
def function():
global ostr
exec("global ostr; ostr = nstr")
#global ostr; ostr = nstr
print(ostr)
lv='ostr' in globals()
print(lv)
ostr='asd'
作業過
真的
編輯:剛剛意識到 exec 實際上與全域變數一起作業,如果您重新運行代碼并在全域 main 中列印(ostr),您將看到它已更改。
ostr = "didn't work"
nstr = "worked"
def function():
#global ostr
exec("global ostr; ostr = nstr")
function()
print(ostr)
作業過
編輯#2:要么在修改 ostr 之前將其宣告為全域變數,要么將其分配給另一個區域變數。
ostr = "didn't work"
nstr = "worked"
def function():
exec("global ostr; ostr = nstr")
#global ostr; ostr = nstr
print(ostr)
lv='ostr' in globals()
print(lv)
function()
作業過
真的
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/362111.html
