我当时遇到一个错误,名称“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/