python全局变量一定要用global来做声明吗?
这段代码不用在函数中声明global x
就可以打印出x的值
x = 20
def getx():
print x
getx()
那请问在哪些情况下必须要使用global
声明全局变量?
以下是一个多线程的python代码片段,其中的x,l
都是全局变量,但在threadcode()
函数中只声明了global x
没有global l
。完整的代码是可以成功运行,但是把global x
注释掉后就会报错。请问这是为什么,Lock对象比较特殊吗?
import threading, time, sys
x = 50
l = threading.Lock()
def threadcode():
global x
l.acquire()
print 'Thread %s invoked.' % threading.currentThread().getName()
try:
print 'Thread %s running.' % threading.currentThread().getName()
x = x + 50
print 'Thread %s set x to %d.' % \
(threading.currentThread().getName(), x)
finally:
l.release()
...
对于Python2而言,对于一个全局变量,你的函数里如果只使用到了它的值,而没有对其赋值(指a = XXX
这种写法)的话,就不需要声明global。相反,如果你对其赋了值的话,那么你就需要声明global
。声明global
的话,就表示你是在向一个全局变量赋值,而不是在向一个局部变量赋值。
Python的作用域解析是基于叫做LEGB(Local(本地),Enclosing(封闭),Global(全局),Built-in(内置))的规则进行操作的。看下面的例子
>>> x = 10
>>> def foo():
... x += 1
... print x
...
>>> foo()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in foo
UnboundLocalError: local variable 'x' referenced before assignment
这是因为,在一个作用域里面给一个变量赋值的时候,Python自动认为这个变量是这个作用域的本地变量,并屏蔽作用域外的同名的变量。很多时候可能在一个函数里添加一个赋值的语句会让你从前本来工作的代码得到一个UnboundLocalError
。
下面的是文档中的解释:
This is because when you make an assignment to a variable in a scope, that variable becomes local to that scope and shadows any similarly named variable in the outer scope.
在使用列表(lists)的时候,很容易就触发这种错误。看下面这个例子:
>>> lst = [1, 2, 3]
>>> def foo1():
... lst.append(5) # 这没有问题...
...
>>> foo1()
>>> lst
[1, 2, 3, 5]
>>> lst = [1, 2, 3]
>>> def foo2():
... lst += [5] # ... 这就有问题了!
...
>>> foo2()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in foo
UnboundLocalError: local variable 'lst' referenced before assignment
玩蛇网文章,转载请注明出处和文章网址:https://www.iplaypy.com/wenda/wd20244.html
相关文章 Recommend
- • 2019年3月最新消息: Python 3.4.10 现已推出
- • [上海]招Python量化系统开发工程师
- • 优集品网络科技有限公司招Python中/高级工程师
- • 爱因互动科技发展有限公司招募Python开发攻城狮
- • mozio招聘Python/Django工程师
- • Kavout金融科技公司招Python研发工程师
- • Python数组逆向输出,编程练习题实例四十
- • Python数组插入排序,编程练习题实例三十九
- • Python矩阵for循环应用,编程练习题实例三十八
- • Python操作Redis数据库方面的问题
- • 请python高手帮我看看这段python代码中函数setter的
- • Python什么方法可以快速将两个队列变成字典
必知PYTHON教程 Must Know PYTHON Tutorials
- • python 解释器
- • python idle
- • python dir函数
- • python 数据类型
- • python type函数
- • python 字符串
- • python 整型数字
- • python 列表
- • python 元组
- • python 字典
- • python 集合
- • python 变量
- • python print
- • python 函数
- • python 类定义
- • python import
- • python help
- • python open
- • python 异常处理
- • python 注释
- • python continue
- • python pass
- • python return
- • python global
- • python assert
- • python if语句
- • python break
- • python for循环
- • python while循环
- • python else/elif
- • lambda匿名函数
必知PYTHON模块 Must Know PYTHON Modules
- • os 模块
- • sys 模块
- • re 正则表达式
- • time 日期时间
- • pickle 持久化
- • random 随机
- • csv 模块
- • logging 日志
- • socket网络通信
- • json模块
- • urlparse 解析URL
- • urllib 模块
- • urllib2 模块
- • robotparser 解析
- • Cookie 模块
- • smtplib 邮件
- • Base64 编码
- • xmlrpclib客户端
- • string 文本
- • Queue 线程安全
- • math数学计算
- • linecache缓存
- • threading多线程
- • sqlite3数据库
- • gzip压缩解压
最新内容 NEWS
- • django app提供pv信息的方法是什么
- • Django项目版本升级如何操作?
- • django较多数据传递如何优雅的呈现
- • django1.7获取参数问题求助
- • Django1.7使用内置comment遇到问题
- • python mysql数据库做insert操作时报_mysql_ex
- • 关于python mysql的duplicate insert机制的疑问
- • pymongo使用insert函数批量插入被中断要怎么
- • Python程序员解决棘手问题的常用库
- • 求助关于restfull api接口几个问题
图文精华 RECOMMEND
-
django1.7获取参数问题求助
-
Python程序员解决棘手问题的常用库
-
求问str()同__str__原理上有什么不同
-
scrapy框架里面用link extractor怎么能
-
python {}.fromkeys创建字典append添加操
-
python3 类型Type str doesn't support th
热点文章 HOT
- 学习Python有什么好的书籍推荐?
- Python匿名函数 Lambda表达式作用
- Python与Java、C、Ruby、PHP等编程语言有什么
- Python 正则中文网页字符串提取问题
- 如何为实时性应用存取经纬度?django my
- 想用python做个客户端,在二维码登录这个地
- 有让IDE可识别Python函数参数类型的方法吗
- Python字符串转换成列表正则疑问