global and local
来源:互联网 发布:手机淘宝互刷平台 编辑:程序博客网 时间:2024/04/29 13:23
from: http://blog.chinaunix.net/u2/82912/showart_2191787.html
and http://zhouzaibao.javaeye.com/blog/559381
http://www.cnblogs.com/ms_config/articles/1685018.html
如果内部函数有引用外部函数的同名变量,并且对这个变量有修改.那么python会认为它是一个局部变量.
解决方法:引用的时候,再次:
global all_length
"local variable referenced before assignment"的几种列子
>>> def max(a):
... if a > 0:
... b = 1
... print b
...
>>> max(1)
1
>>> max(0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 4, in max
UnboundLocalError: local variable 'b' referenced before assignment
这种错误当代码少的时候容易发现,比较难办的就是,当你的代码很多,然后中间隔了很多行以后,再去调用b这个变量的时候,很难去发现这个问题。
解决办法:
1.把if-else写全,这样每种情况都会对b进行定义
2.在if之前给b一个默认值。这样的好处就是代码量小。
2)这种情况是局部变量和全局变量访问的问题。
首先看一个列子
#!/usr/bin/python
#global varibale
USER_COUNT = 0
#function
def main():
adduser()
def adduser():
print 'There are', USER_COUNT, 'users so far'
# actually run main()
main()
再看这一段,注意函数adduser()
#!/usr/bin/python
#global varibale
USER_COUNT = 0
#function
def main():
adduser()
def adduser():
USER_COUNT = USER_COUNT + 1
print 'There are', USER_COUNT, 'users so far'
main()
想明白这点,就要知道python对变量访问的规则
当搜索一个变量的时候,python先从局部作用域开始搜索,如果在局部作用域没有找到那个变量,那样python就在全局变量中找这个变量,如果找不到抛出异常(NAMEERROR 或者 Unbound-
LocalError,这取决于你使用的python 版本。)
知道了对变量的访问规则,那就开始我们的解决办法
1.在函数adduser中加”global USER_COUNT“,就可以对全局变量进行操作。
def adduser():
global USER_COUNT
USER_COUNT = USER_COUNT + 1
print 'There are', USER_COUNT, 'users so far'
2.在函数adduser中对变量”USER_COUNT“进行定义(这种情况,相当于使用一个新的变量,但是一个局部变量和一个全局变量同名是一件很不好的事情)
def adduser():
USER_COUNT = 0
USER_COUNT = USER_COUNT + 1
print 'There are', USER_COUNT, 'users so far'
3)先把例子留到这里吧,因为自己还不是太明白这个,希望高手帮忙
def bankAccount():
bal=0
def credit(amount):
bal=bal+amount
def debit(amount):
bal=bal-amount
def balance():
return bal
return (lambda x: {"credit":credit,
"debit":debit,
"balance":balance
}[x])
b=bankAccount()
print b("balance")()
b("credit")(100)
- global and local
- Global and Local Variables
- Local and Global References
- Global and Local Variables
- Local and Global References区别
- global variable and local variable
- Global and Local Variables python
- Local Reference and Global Reference
- python global and local variable
- JNI学习之-----Local and Global References
- local index and global index [转]
- Learning with Local and Global Consistency
- Unity's Rotation:local and global
- Local & Global
- Questions about OPENCL global and local work size
- Learning with local and global consistency阅读报告NIPS2003
- local|global index
- Global 和 Local 索引。
- 文件数据基础知识
- Linux TCP/IP 协议栈的关键数据结构Socket Buffer(sk_buff )
- 深入 CSocket 编程之阻塞和非阻塞模式
- 【转载】关于计算机专业找工作的建议
- 将程序锁定到任务栏
- global and local
- 列名(栏位)引用其它表的内容替换查询、批量替换列名(栏位)应用实例
- 明明白白看MFC之程序框架
- STL中提供-二分查找算法
- 如何杀蟑螂最有效
- 彻底堵死SQL注入工具漏洞
- Oracle OSB和Oracle ESB的区别
- 理一下要做的事
- 数据结构002 - 二叉查找树(BST)