亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

這可能涉及名稱空間,但我無法弄清楚為什么在一個示例中找不到該名稱,但在另一個示例中卻找到了

這可能涉及名稱空間,但我無法弄清楚為什么在一個示例中找不到該名稱,但在另一個示例中卻找到了

偶然的你 2022-12-27 17:18:34
所以我有兩個簡單的 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()


查看完整回答
反對 回復 2022-12-27
  • 1 回答
  • 0 關注
  • 116 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號