在嵌套函数中使用全局引用

Flu*_*per 2 python

当时我遇到了一个错误,即未定义名称“start”,尽管我在嵌套的内部将其声明为全局,但我知道还有另一种方法是更改​​ BS 函数的签名以开始和结束变量,但我需要知道如何使用全局方法解决它,谢谢!

class math:
    def search(self,nums,x):
        start = 0
        end = len(nums)

        def BS():
            global start
            global end

            while(start<=end):
                #i assign  here  a new value to start and end

        first = BS()
        return first
Run Code Online (Sandbox Code Playgroud)

dvl*_*per 5

使用nonlocal,所以类似于:

class math:
    def search(self,nums,x):
        start = 0
        end = len(nums)

        def BS():
            nonlocal start
            nonlocal end

            while(start<=end):
                pass # use pass if you want to leave it empty!
                #i assign  here  a new value to start and end

        first = BS()
        return first
Run Code Online (Sandbox Code Playgroud)

也许你会发现很有帮助!

  • 确切地。@Flupper,它起作用的原因是,当您第一次定义“start”时,Python 将其视为“search”函数的本地函数。当在“BS”函数中声明“global start”时,Python 假定这必须是与前一个“start”实例不同的变量,因为该变量不是全局的。 (2认同)