Python 函数:如果仅访问全局变量,则传递全局变量? [英] Python functions: Pass global variables if only accessing them?
问题描述
我正在尝试了解 Python 中的最佳实践.如果我定义一个函数来访问(但不更改)全局变量,则通常不需要在函数中将该变量指定为全局变量.但是将全局变量传递给函数是否更快?我之所以这么问是因为我遇到了一些关于查找全局变量的成本的参考,但我不确定我是否理解.例如:
I'm trying to get a sense of best practices in python. If I define a function to access (but not change) a global variable, it's not generally necessary to specify the variable as global in the function. But is it faster to pass the global variable to the function? I ask because I've come across some references to the cost of looking up global variables, but I'm not sure that I understand. For example:
def f1(localList):
for element in localList:
if element in globalSet:
pass #do stuff.
def f2(localList, localSet):
for element in localList:
if element in localSet:
pass #do stuff.
globalList = <arbitrary list>
globalSet = <arbitrary set>
f1(globalList)
f2(globalList, globalSet)
与 f1 相比,f2 是否通常被认为是更快/更好/更pythonic"的方法?
is f2 generally considered to be the faster/better/more "pythonic" approach compared to f1?
推荐答案
使用 Globals 总是一个糟糕的设计选择.无论如何,你总能想出一个不使用 Globals 的解决方案,它会更像 Pythonic.
Using Globals is always a bad design choice. In any case you can always come up with a solution which would be more Pythonic by not using Globals.
- 如果你必须在函数之间共享很多变量,你可以重新考虑面向对象的方法.
- 如果你必须将许多参数传递给一个函数,您可以选择 varargs 或 kargs.
记住,参数是通过引用传递的,所以没有效率损失.
Remember, parameters are passed by reference so there is no efficiency lost.
----特殊情况不足以打破规则.
这篇关于Python 函数:如果仅访问全局变量,则传递全局变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!