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
    评论
Python中,要在函数内部使用全局变量,可以使用global关键字将变量声明为全局变量。首先,在函数外部给变量赋初值,然后在函数内部使用global关键字声明该变量全局变量。例如,如果有一个全局变量a,在函数内部需要使用它,可以在函数内部使用"global a"来声明a为全局变量,然后就可以使用a了。需要注意的是,不能在global语句中同时给变量赋值,只能在global语句之前先给变量赋值。比如,要将a设置为5,应该先使用global a声明a为全局变量,然后再将a设置为5,即global a a=5。这样,函数内部就可以使用全局变量a了。 请参考以了解更多关于在Python函数调用全局变量的方法和注意事项。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *3* [Python如何在函数内部使用全局变量](https://blog.csdn.net/hnjzsyjyj/article/details/121433141)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* [python函数里引用全局变量](https://blog.csdn.net/edward_zcl/article/details/116163319)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值