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

所以我有两个简单的 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

我敢肯定有人知道发生了什么,但我很茫然。


偶然的你
浏览 100回答 1
1回答

慕斯709654

这确实是标识符范围的问题。在您的test1.pya中,标识符b和d在函数的范围内是未知的fmt,因为它们既不是全局的(这就是使它们在您的test2.py中已知的原因),也不是本地的。您可以使用nonlocal内部语句解决此问题fmt:def main():&nbsp; &nbsp; def fmt(*args):&nbsp; &nbsp; &nbsp; &nbsp; nonlocal a, b, d # <----------- only added line of code&nbsp; &nbsp; &nbsp; &nbsp; r = ""&nbsp; &nbsp; &nbsp; &nbsp; for x in args:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; r += eval("f'"+x+"'")&nbsp; &nbsp; &nbsp; &nbsp; return r&nbsp; &nbsp; a = "alpha"&nbsp; &nbsp; b = "beta"&nbsp; &nbsp; d = "delta"&nbsp; &nbsp; msg = "Hello {d} one, this is {a} {b}"&nbsp; &nbsp; print(msg)&nbsp; &nbsp; print(fmt(msg))if __name__ == "__main__":&nbsp; &nbsp; main()
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python