Lok*_*esh 1 python recursion global
我正在实现一个递归函数,我需要记住一个全局值.我将在每次递归调用中减少此值,并希望它也反映在其他递归调用中.
这是我做过的一种方式.
第一种方式:
global a
a = 3
def foo():
global a
if a == 1:
print 1
return None
print a
a -= 1 # This new 'a' should be available in the next call to foo()
foo()
Run Code Online (Sandbox Code Playgroud)
输出:
3
2
1
Run Code Online (Sandbox Code Playgroud)
但我想用另一种方式,因为我的教授说全局变量是危险的,应该避免使用它们.
另外,我不是简单地将变量'a'作为参数传递,因为在我的实际代码中'a'只是为了跟踪一些数字,即跟踪我首先访问的节点的编号.所以,我不想通过在每个调用中引入'a'作为参数来使我的程序复杂化.
请建议我解决上述问题的最佳编程实践.
不要使用全球; 只需a为函数创建一个参数:
def foo(a):
print a
if a == 1:
return None
foo(a-1)
foo(3)
Run Code Online (Sandbox Code Playgroud)
试试这个:使用参数而不是全局变量.示例代码
a = 3
def foo(param):
if param == 1:
print 1
return None
print param
foo(param - 1)
foo(a)
Run Code Online (Sandbox Code Playgroud)