所以我有兩個簡單的 Python 模塊:test1.py:def main(): def fmt(*args): r = "" for x in args: r += eval("f'"+x+"'") return r a = "alpha" b = "beta" d = "delta" msg = "Hello xr8t8au one, this is {a} " print(msg) print(fmt(msg))if __name__ == "__main__": main()和 test2.py:def fmt(*args): r = "" for x in args: r += eval("f'"+x+"'") return ra = "alpha"b = "beta"d = "delta"msg = "Hello wczradr one, this is {a} "print(msg)print(fmt(msg))所以,基本上是相同的,除了第一個將代碼包裝在一個函數中,而第二個沒有。第一個在執行時給出以下輸出:Hello aj82k7s one, this is {a} Traceback (most recent call last): File "test1.py", line 16, in <module> main() File "test1.py", line 13, in main print(fmt(msg)) File "test1.py", line 6, in fmt r += eval("f'"+x+"'") File "<string>", line 1, in <module>NameError: name 'd' is not defined第二個如我所料:Hello 2l35b6b one, this is {a} Hello delta one, this is alpha beta所以第一個認為它不知道這個d名字。但是,如果我print(dir(d))在語句之后立即插入 test1.py def fmt(*args):,現在它會找到d,然后不知道下一個名稱a:Hello nxa5voo one, this is {a} Traceback (most recent call last): File "test1.py", line 17, in <module> main() File "test1.py", line 14, in main print(fmt(msg)) File "test1.py", line 7, in fmt r += eval("f'"+x+"'") File "<string>", line 1, in <module>NameError: name 'a' is not defined我敢肯定有人知道發生了什么,但我很茫然。
1 回答

慕斯709654
TA貢獻1840條經驗 獲得超5個贊
這確實是標識符范圍的問題。在您的test1.pya中,標識符b和d在函數的范圍內是未知的fmt,因為它們既不是全局的(這就是使它們在您的test2.py中已知的原因),也不是本地的。您可以使用nonlocal內部語句解決此問題fmt:
def main():
def fmt(*args):
nonlocal a, b, d # <----------- only added line of code
r = ""
for x in args:
r += eval("f'"+x+"'")
return r
a = "alpha"
b = "beta"
d = "delta"
msg = "Hello 1pa689i one, this is {a} "
print(msg)
print(fmt(msg))
if __name__ == "__main__":
main()
添加回答
舉報
0/150
提交
取消