Python函数:如果仅访问全局变量,则传递全局变量? [英] Python functions: Pass global variables if only accessing them?
问题描述
我试图了解python的最佳实践。如果我定义一个函数来访问(但不能改变)全局变量,通常不需要在函数中指定该变量为全局变量。但是将全局变量传递给函数会更快吗?我问,因为我遇到了查找全局变量成本的一些参考,但我不确定我的理解。例如:
def f1(localList):
用于localList中的元素:
if global中的元素:
传递#do东西。
def f2(localList,localSet):
用于localList中的元素:
如果localSet中的元素为:
传递#do stuff。
globalList =<任意列表>
globalSet =<任意集合>
f1(globalList)
f2(globalList,globalSet)
是f2通常被认为是比f1更快/更好/更pythonic的方法吗?解决方案
使用Globals总是一个糟糕的设计选择。在任何情况下,你总是可以想出一个解决方案,通过不使用Globals来更加Pythonic。
- 如果你必须分享很多函数之间的变量,你可以
重新考虑OO方法。 - 如果您必须将许多参数传递给
函数,则可以选择可变参数或可变参数。
请记住,参数是通过引用传递的,所以没有效率损失。
----特殊情况不够特殊打破规则。
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)
is f2 generally considered to be the faster/better/more "pythonic" approach compared to f1?
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.
- If you have to share lot of variables between functions, you can reconsider an OO approach.
- If you have to pass many parameter's to a functions, you can opt for varargs or kargs.
Remember, parameters are passed by reference so there is no efficiency lost.
----Special cases aren't special enough to break the rules.
这篇关于Python函数:如果仅访问全局变量,则传递全局变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!