我的函数什么时候会转到以前的作用域来查找变量



在python 3.0中,根据我所知,当我使用在本地范围内找不到的变量时,它会一直返回,直到到达全局范围来寻找该变量。

我有这个功能:

def make_withdraw(balance):
    def withdraw(amount):
        if amount>balance:
            return 'insuffiscient funds'
        balance=balance-amount
        return balance
    return withdraw
p=make_withdraw(100)
print(p(30))

当我插入一行时:

nonlocal balance

在撤回函数定义下,它运行良好,但如果我不这样做,它会给我一个错误,即我在赋值之前引用了局部变量balance,即使我在makewithdraw函数范围或全局范围中有它。

为什么在其他情况下,它会在以前的作用域中找到变量,而在这次作用域中却找不到?

谢谢!

关于这个主题的问题太多了。你应该先搜索一下再询问。

基本上,由于函数withdraw中有balance=balance-amount,Python认为balance是在该函数中定义的,但当代码运行到if amount>balance:行时,它没有看到balance的定义/赋值,因此它抱怨local variable 'balance' before assignment

nonlocal允许您将值分配给外部(但非全局)作用域中的变量,它告诉python balance不是在函数withdraw中定义的,而是在函数CCD-9外部定义的。

最新更新