所以我有两个简单的 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 r
a = "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
我敢肯定有人知道发生了什么,但我很茫然。
慕斯709654
相关分类