python - 在嵌套函数内使用全局引用

标签 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

最佳答案

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

也许你会发现this有帮助!

关于python - 在嵌套函数内使用全局引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61881569/

相关文章:

python - 如何比较包含整数的列表 A 和列表 B 并打印缺少的整数?

python - python字典中keys()和values()的顺序是否保证相同?

Python:查找点是否位于多边形的边界上

python - 如何访问和修改 Django 模板上下文变量

python - 如何打印回溯堆栈中的第一行

Python。定义 "attribute initial method"

python - 无法分配ndarray

python - 如何解压pkl文件?

python - 如何使用 TensorFlow tf.train.string_input_producer 产生多个 epochs 的数据?

python - 如何使用 python 包分发数据文件以使其可读?