首页 > 解决方案 > 在嵌套函数中使用全局引用

问题描述

我当时遇到一个错误,没有定义名称'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

标签: python

解决方案


使用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

也许你会发现很有帮助!


推荐阅读