所以我有两个简单的 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 {d} one, this is {a} {b}" 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 {d} one, this is {a} {b}"print(msg)print(fmt(msg))所以,基本上是相同的,除了第一个将代码包装在一个函数中,而第二个没有。第一个在执行时给出以下输出:Hello {d} one, this is {a} {b}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 {d} one, this is {a} {b}Hello delta one, this is alpha beta所以第一个认为它不知道这个d名字。但是,如果我print(dir(d))在语句之后立即插入 test1.py def fmt(*args):,现在它会找到d,然后不知道下一个名称a:Hello {d} one, this is {a} {b}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 {d} one, this is {a} {b}"
print(msg)
print(fmt(msg))
if __name__ == "__main__":
main()
添加回答
举报
0/150
提交
取消