闭包-Python


#闭包函数类似class;子函数类似闭包的def(self),属性类似class的private属性
#闭包在变量使用上更有限制性:如果是class,属性可以是任意变量可以做任意更改,如果是闭包,局部变量只能被引用,不能被修改(除非是容器变量/可变变量)
CASE:
------------------------------------------------------------闭包函数--------------------------------------------------------
origin = [0, 0] # 坐标系统原点
legal_x = [0, 50] # x轴方向的合法坐标
legal_y = [0, 50] # y轴方向的合法坐标


def create(pos=origin):
def player(direction, step):
# 这里应该首先判断参数direction,step的合法性,比如direction不能斜着走,step不能为负等
# 然后还要对新生成的x,y坐标的合法性进行判断处理,这里主要是想介绍闭包,就不详细写了。
new_x = pos[0] + direction[0] * step
new_y = pos[1] + direction[1] * step
pos[0] = new_x
pos[1] = new_y
# 注意!此处不能写成 pos = [new_x, new_y],原因在上文有说过
return pos

return player


player = create() # 创建棋子player,起点为原点
print player([1, 0], 10) # 向x轴正方向移动10步
print player([0, 1], 20) # 向y轴正方向移动20步
print player([-1, 0], 10) # 向x轴负方向移动10步

################################################################相同功能的类########################################
origin = [0, 0] # 坐标系统原点
legal_x = [0, 50] # x轴方向的合法坐标
legal_y = [0, 50] # y轴方向的合法坐标


class create():
def __init__(self,origin):
self.pos = origin
def player(self,direction, step):
# 这里应该首先判断参数direction,step的合法性,比如direction不能斜着走,step不能为负等
# 然后还要对新生成的x,y坐标的合法性进行判断处理,这里主要是想介绍闭包,就不详细写了。
new_x = self.pos[0] + direction[0] * step
new_y = self.pos[1] + direction[1] * step
self.pos[0] = new_x
self.pos[1] = new_y
# 注意!此处不能写成 pos = [new_x, new_y],原因在上文有说过
print self.pos

c=create(origin)
c.player([1,0],10)
c.player([0,1],20)
c.player([-1,0],10)
-----------------------------------------------------练习----------------------------------------------------------
def foo():
a = []
def bar():
a.append(100)
return a
return bar

if __name__ == "__main__":
b = foo()
c = foo()

print b()
print b()
print c()
posted @ 2019-03-30 13:38  小鱼biubiu  阅读(148)  评论(0编辑  收藏  举报