python 函数调用全局变量_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 =

globalSet =

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值