利用python闭包性质写只用函数来写一个类
2017-12-29 00:00
441 查看
把函数当成类用
版本一:保存内部状态的
运行结果:
123 456
321 222
444 678
442 676
0 0
版本二:纯函数的
参考自:python学习笔记 - local, global and free variable https://www.jianshu.com/p/e1fd4f14136a
版本一:保存内部状态的
# -*- 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
相关文章推荐
- 学习笔记之Python 切片:利用切片操作,实现一个trim()函数,去除字符串首尾的空格
- Python中有关函数作为一个函数的返回值(闭包)
- 【廖雪峰 python教程 课后题 切片】利用切片操作,实现一个trim()函数,去除字符串首尾的空格,注意不要调用str的strip()方法:
- 利用闭包返回一个计数器函数,每次调用它返回递增整数:
- Python学习笔记——利用闭包写递增函数
- Python(10)使用python函数实现一个简单的闭包操作
- Python 切片:利用切片操作,实现一个trim()函数,去除字符串首尾的空格
- 【廖雪峰 python教程 课后题 切片】利用切片操作,实现一个trim()函数,去除字符串首尾的空格,注意不要调用str的strip()方法:
- 利用闭包把Python函数当类使
- 利用Python与HFSS联合仿真设计一个微带天线
- python小程序,编写一个函数,接受list并用reduce求积
- 一个Python中的闭包问题
- Python中的函数对象与闭包
- python:将一个外部函数,转化为类中的方法
- 利用node实现一个批量重命名文件的函数
- C#中利用函数判断一个数是否为回文…
- Python函数小结(1)--参数类型(*, ** 的区别), 闭包
- 利用函数将一个浮点型变量转化为二进制
- python3 第二十一章 - 函数式编程之return函数和闭包
- python函数对象和闭包