您的位置:首页 > 编程语言 > Python开发

利用python闭包性质写只用函数来写一个类

2017-12-29 00:00 441 查看
把函数当成类用

版本一:保存内部状态的

# -*- 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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息