1.作用域
global语句
用于声明一个全局变量
this_is_global = "abc"
def func():
global this_is_global
this_is_global = "global"
print this_is_global
func()
print this_is_global
嵌套作用域
Python2.1之前只允许两个作用域:局部作用域和全局作用域。Python2.1之后的便支持嵌套作用域,代码如下所示:
def foo():输出:
def bar():
print "bar"
n = 4
print m + n
print "foo"
m = 3
bar()
foo()
foo
bar
7
bar
7
以下代码会报错:
def foo():错误:NameError: free variable 'm' referenced before assignment in enclosing scope
def bar():
print "bar"
n = 4
print m + n
print "foo"
bar()
m = 3
foo()
搜索作用域
1.python 先从局部作用域开始搜索,没找到则在全局域继续搜索,否则就会抛出 NameError 异常;
2.全局变量能被同名的局部变量所覆盖;
3.变量的作用域受到命名空间的影响。
闭包
如果在一个内部函数里,对在外部的非全局作用域的变量进行引用,那么内部函数就被认为是 closure(闭包)。使用闭包来代替类实现某个功能是个不错的注意。
计数器:
def counter(start_at = 0):
count = [start_at]
def incr():
count[0] += 1
return count[0]
return incr
count1 = counter(5) #新建函数对象
print count1()
print count1()
print count1()
count2 = counter(5) #新建函数对象
print count2()
print count2()
print count1()
print count1()
print count1()
输出:
6
7
8
6
7
9
10
11
7
8
6
7
9
10
11
验证器:
def max_length(n):
def validator(s):
if len(s) < n:
return
raise Exception('Length of string must be less than {0}!'.format(n))
return validator
生成器
简版:
def simpleGen():
yield 1
yield "2->punch!"
myG = simpleGen()
print myG.next()
print myG.next()
for循环版:
from random import randint
def randGen(aList):
while len(aList) > 0:
yield aList.pop(randint(0, len(aList) - 1))
for item in randGen(['rock', 'paper', 'scissors']):
print item
def tt():
for x in xrange(4):
yield "tt+" + str(x)
def yy():
for x in xrange(4):
yield "yy+" + str(x)
from Queue import Queue
class TaskMgr:
def __init__(self):
self.task_q = Queue()
def add(self, task):
self.task_q.put(task)
def run(self):
while not self.task_q.empty():
for i in xrange(self.task_q.qsize()):
try:
gen = self.task_q.get()
print gen.next()
except StopIteration:
print str(i) + "Stop."
pass
else:
self.task_q.put(gen)
t = TaskMgr()
t.add(tt())
t.add(yy())
t.run()