当时我遇到了一个错误,即未定义名称“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)
使用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)
也许你会发现这很有帮助!