python关键字nonlocal和global的区别


关键字nonlocal:是python3.X中出现的,所以在python2.x中无法直接使用.

python引用变量的顺序为: 当前作用域局部变量->外层作用域变量->当前模块中的全局变量->python内置变量

python中关键字nonlocal和global区别:
一:global关键字用来在函数或其它局部作用域中使用全局变量。但是如果不使用全局变量也可以不适用global关键字声明。

Python
In [1]: gcount = 0 In [2]: def get_global(): ...: #不修改时,不用使用global关键字 ...: return gcount ...: In [3]: def global_add(): ...: #修改时,需要使用global关键字 ...: global gcount ...: gcount += 1 ...: return gcount ...: In [4]: get_global() Out[4]: 0 In [5]: global_add() Out[5]: 1 In [6]: global_add() Out[6]: 2 In [7]: get_global() Out[7]: 2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
In [ 1 ] : gcount = 0
 
In [ 2 ] : def get_global ( ) :
   . . . :      #不修改时,不用使用global关键字
   . . . :      return gcount
   . . . :
 
In [ 3 ] : def global_add ( ) :
   . . . :      #修改时,需要使用global关键字
   . . . :      global gcount
   . . . :      gcount += 1
   . . . :      return gcount
   . . . :
 
In [ 4 ] : get_global ( )
Out [ 4 ] : 0
 
In [ 5 ] : global_add ( )
Out [ 5 ] : 1
 
In [ 6 ] : global_add ( )
Out [ 6 ] : 2
 
In [ 7 ] : get_global ( )
Out [ 7 ] : 2

二:nonlocal关键字用来在函数或其它作用域中使用外层(非全局)变量

Python
In [8]: def make_counter(): ...: count = 0 ...: def counter(): ...: nonlocal count ...: count += 1 ...: return count ...: return counter ...: In [9]: counter = make_counter() In [10]: counter() Out[10]: 1 In [11]: counter() Out[11]: 2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
In [ 8 ] : def make_counter ( ) :
   . . . :      count = 0
   . . . :      def counter ( ) :
   . . . :          nonlocal count
   . . . :          count += 1
   . . . :          return count
   . . . :      return counter
   . . . :
 
In [ 9 ] : counter = make_counter ( )
 
In [ 10 ] : counter ( )
Out [ 10 ] : 1
 
In [ 11 ] : counter ( )
Out [ 11 ] : 2

在python2中可以设置可变变量来实现,例如列表,字典等。

链接:https://www.jianshu.com/p/ab69b83a8d8a




  • zeropython 微信公众号 5868037 QQ号 5868037@qq.com QQ邮箱
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值