gpt4 book ai didi

python - 这可能涉及 namespace ,但我无法弄清楚为什么在一个示例中找不到该名称,但在另一个示例中找到了

转载 作者:行者123 更新时间:2023-12-04 17:05:44 28 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





UnboundLocalError with nested function scopes

(4 个回答)


去年关闭。




所以我有两个简单的 Python 模块:
测试1.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))def fmt(*args): 之后立即进入 test1.py语句,现在找到 d ,然后不知道下一个名字, a :
Hello {d} one, this is {a} {b}
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
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

我相信有人明白发生了什么,但我不知所措。

最佳答案

这确实是标识符范围的问题。在您的 test1.py , 标识符 a , bd在函数作用域内未知 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()

关于python - 这可能涉及 namespace ,但我无法弄清楚为什么在一个示例中找不到该名称,但在另一个示例中找到了,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62204003/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com