简体   繁体   English

Python递归:与仅声明全局变量并在函数中重新声明相比,传递所有变量是否有任何优势?

[英]Python Recursion: Are there any advantages to passing all variables vs just declaring a global variable and re-declaring in the function?

When I look at python code I see two styles of handling variables in python. 当我查看python代码时,我看到了python中处理变量的两种样式。

  1. pass all variables. 传递所有变量。

Example

#initialize
variable1 = 1
variable2 = 1
variable3 = 1

def recursive(variable1, variable2, variable3):
    do stuff with variables
    recursive(variable1, variable2, variable3)
  1. if a variable doesn't need a separate instance inside the function, just make it global 如果变量在函数内不需要单独的实例,则将其设置为全局

example

#initialize
variable1 = 1
global variable2 
variable2 = 1
global variable3 
variable3 = 1

def recursive(variable1):
    global variable2
    global variable3
    do stuff variables
    recursive(variable1)

Are there any advantages to either style? 两种风格都有什么优点吗? Is one more 'pythonic' than the other? 一个比另一个更“ pythonic”吗?

Using global excessively can be tricky to debug. 过度使用global可能很难调试。 The pythonic way is definitely to pass everything explicitly or encapsulate the work into smaller functions so that there isn't so much verbosity messing with all three variables. pythonic方式肯定是将所有内容显式传递或将工作封装到较小的函数中,以使所有这三个变量不会太冗长。

In your case, there might be an easier approach: 在您的情况下,可能有一种更简单的方法:

def recursive(*args)
    # Do stuff with args
    recursive(*args)

This eliminates a lot of the verbosity you might not have cared for. 这消除了很多您可能不需要关心的冗长的细节。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM