在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/Python/ Python 嵌套函數中使用上層函數變量的問題?

Python 嵌套函數中使用上層函數變量的問題?

為什么下面三個函數中的最后兩個會出現異常而第一個不會?

def func(lst=[]):
    def inner_func():
        lst.append(10)
        return lst
    return inner_func()


def func2(num=10):
    def inner_func():
        num += 1
        return num
    return inner_func()


def func3(lst=[]):
    def inner_func():
        lst += [10]
        return lst
    return inner_func()


if __name__ == '__main__':
    print('func:', func())

    try:
        print('func2:', func2())
    except UnboundLocalError as e:
        print('func2:', e)

    try:
        print('func3:', func3())
    except UnboundLocalError as e:
        print('func3:', e)

執(zhí)行結果:

func: [10]
func2: local variable 'num' referenced before assignment
func3: local variable 'lst' referenced before assignment
回答
編輯回答
避風港

python的變量作用域分為legb(隨便找了一個博文你可以了解一下

在func2和func3中你對num、lst進行了賦值操作,導致這兩個變量為局部作用域,而局部變量中又沒有初始值(num += 1等價為num = num + 1),所以報錯。

clipboard.png

2017年2月25日 22:35