这两天在学习python相关的知识,发现装饰器是一种使该编程语言更加pythonic的东西,接触学习后又引出了闭包相关的知识,于是花时间看了看相关知识并自己敲了下往上给出的比较经典的闭包的相关练习来加深印象。下面是闭包中比较又代表性的两个应用实例,代表了闭包的两大功能:
#-*-coding:utf-8-*-
#闭包的功能1:保存当前的环境(保存当前运行后外层函数形参变量的状态)
origin = [0, 0]
def move(pos = origin):
def go(direction, step):
pos[0] = pos[0] + direction[0] * step
pos[1] = pos[1] + direction[1] * step
return pos
return go
player = move()
print(player([0, 1], 10))
print(player([1, 0], 20))
#闭包功能2:可以根据外层函数的局部变量得到不同的结果
def find_str(keep):
def find(file_name):
with open (file_name, "r") as f:
res = [i for i in f.readlines() if keep in i]
return res
return find
file_name = "1.txt"
keep = "23"
search_in = find_str(keep)
print search_in(file_name)