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
也许你会发现这很有帮助!
推荐阅读
- c# - Open-XML 文档没有内容
- reactjs - vs 代码转到定义不起作用 React Native
- javascript - Jquery .html() 正在删除单词之间的空格
- python - 给定 N 个变量和范围,生成 K 个随机 numpy 数组
- css - 在测验中更改所选选项的颜色
- reactjs - 加载反应应用程序时如何仅调度一次redux操作?
- r - 将数据帧中的每一行与 r 中另一个数据帧中的每一行匹配
- php - 如何使用 str 替换正则表达式进行深度替换?
- next.js - Next js中具有多个参数的动态路由-文件结构
- javascript - Brotli/gzip 压缩启用但不工作?