python语法32[global与nonlocal比较]
2011-12-31 13:10
447 查看
python引用变量的顺序: 当前作用域局部变量->外层作用域变量->当前模块中的全局变量->python内置变量
一 global
global关键字用来在函数或其他局部作用域中使用全局变量。但是如果不修改全局变量也可以不使用global关键字。
gcount = 0
def global_test():
print (gcount)
def global_counter():
global gcount
gcount +=1
return gcount
def global_counter_test():
print(global_counter())
print(global_counter())
print(global_counter())
二 nonlocal
nonlocal关键字用来在函数或其他作用域中使用外层(非全局)变量。
def make_counter():
count = 0
def counter():
nonlocal count
count += 1
return count
return counter
def make_counter_test():
mc = make_counter()
print(mc())
print(mc())
print(mc())
也可以使用generator来实现类似的counter。如下:
def counter_generator():
count = 0
while True:
count += 1
yield count
def counter_generator_test():
# below is for python 3.x and works well
citer = counter_generator().__iter__()
i = 0
while(i < 3) :
print(citer.__next__())
i+=1
def counter_generator_test2():
#below code don't work
#because next() function still suspends and cannot exit
#it seems the iterator is generated every time.
j = 0
for iter in counter_generator():
while(j < 3) :
print(iter)
j+=1
完!
一 global
global关键字用来在函数或其他局部作用域中使用全局变量。但是如果不修改全局变量也可以不使用global关键字。
gcount = 0
def global_test():
print (gcount)
def global_counter():
global gcount
gcount +=1
return gcount
def global_counter_test():
print(global_counter())
print(global_counter())
print(global_counter())
二 nonlocal
nonlocal关键字用来在函数或其他作用域中使用外层(非全局)变量。
def make_counter():
count = 0
def counter():
nonlocal count
count += 1
return count
return counter
def make_counter_test():
mc = make_counter()
print(mc())
print(mc())
print(mc())
也可以使用generator来实现类似的counter。如下:
def counter_generator():
count = 0
while True:
count += 1
yield count
def counter_generator_test():
# below is for python 3.x and works well
citer = counter_generator().__iter__()
i = 0
while(i < 3) :
print(citer.__next__())
i+=1
def counter_generator_test2():
#below code don't work
#because next() function still suspends and cannot exit
#it seems the iterator is generated every time.
j = 0
for iter in counter_generator():
while(j < 3) :
print(iter)
j+=1
完!
相关文章推荐
- python语法32[global与nonlocal比较]
- python语法32[global与nonlocal比较]
- python语法[global与nonlocal比较]
- Python的global和nonlocal关键字(学习)
- es6 和 python 语法比较
- python语法32[装饰器decorator](转)
- Python语法基础09.比较、关系运算符
- [python]global与nonlocal关键字
- Python 中 global、nonlocal的使用
- 语法比较:Julia,Matlab,Python
- python基础-方法嵌套、就近原则、global、nonlocal、函数即变量
- python语法31[变量的作用域+global]
- Matlab与Python的语法比较
- Ruby和Python的语法比较
- python:global与nonlocal关键字
- python语法32[装饰器decorator]
- python(第二天):global和nonlocal
- c++、c#、Python、GO语言基本语法比较
- python3中global 和 nonlocal 的作用域
- Python nonlocal 与 global 关键字解析