python闭包两种写法_利用python闭包性质写只用函数来写一个类

把函数当成类用

版本一:保存内部状态的

# -*- coding: utf-8 -*-

"""

Created on Sun Dec 31 12:21:33 2017

@author: zbg

"""

def Point(xx, yy):

def point():

point.x, point.y = xx, yy#这样设计是为了保证每个实例这里只执行一次

def functions(f):

def reset():

point.x = point.y = 0

def addn(n):

point.x += n

point.y += n

def addxy(xx, yy):

point.x += xx

point.y += yy

def getx():

return point.x

def gety():

return point.y

def addP(P):

point.x += P("getx")()

point.y += P("gety")()

def show():

print point.x, point.y

return eval(f)

return functions

return point()

p1 = Point(123,456)

p2 = Point(321,222)

p1("show")()

p2("show")()

p1 ("addP") (p2)

p1("show")()

p1("addn") (-2)

p1("show")()

p1 ("reset")()

p1("show")()

运行结果:

123 456

321 222

444 678

442 676

0 0

版本二:纯函数的

# -*- coding: utf-8 -*-

"""

Created on Sun Dec 31 09:41:16 2017

@author: zbg

"""

def Point(x, y):

def functions(f):

def reset():

return Point(0, 0)

def addn(n):

return Point(x + n, y + n)

def addxy(xx, yy):

return Point(x + xx, y + yy)

def getx():

return x

def gety():

return y

def addP(P):

return Point(x + P("getx")(), y + P("gety")())

def show():

print x, y

return eval(f)

return functions

p1 = Point(123,456)

p2 = Point(321,222)

p1("show")()

p2("show")()

p1 = p1 ("addP") (p2)

p1("show")()

p1 = p1("addn") (-2)

p1("show")()

p1 = p1 ("reset")()

p1("show")()

def Counterx(x):#这个例子是构造函数参数比内部状态少的,里面的s会记录每次改变的x的和。

def counterx(x, s):

def functions(f):

def resets():

return counterx(x, 0)

def getx():

return x

def setx(x):

return counterx(x, s + x)

def show():

print x, s

return eval(f)

return functions

return counterx(x, x)

cx = Counterx(10)

cx("show")()

cx = cx("setx")(9)

cx("show")()

cx = cx("setx")(8)

cx("show")()

cx = cx("resets")()

cx("show")()

参考自:python学习笔记 - local, global and free variable  https://www.jianshu.com/p/e1fd4f14136a

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值