栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何在python函数中使用全局变量?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何在python函数中使用全局变量?

global
在函数内部使用变量,您需要
global <varName>
像这样在函数内部进行操作。

testVar = 0def testFunc():    global testVar    testVar += 1print testVartestFunc()print testVar

给出输出

>>> 01

请记住,

global
如果您要进行分配/更改它们,则只需要在函数内声明它们。
global
打印和访问不需要。

你可以做,

def testFunc2():    print testVar

global
不像我们在第一个函数中那样声明它,它仍然可以正确赋值。

以a

list
为例,您不能在
list
不声明的情况下分配a ,
global
但是可以调用它的方法并更改列表。如下所示。

testVar = []def testFunc1():    testVar = [2] # Will create a local testVar and assign it [2], but will not change the global variable.def testFunc2():    global testVar    testVar = [2] # Will change the global variable.def testFunc3():    testVar.append(2) # Will change the global variable.


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/610565.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号