python闭包,装饰器
来源:互联网 发布:java cms框架搭建 编辑:程序博客网 时间:2024/05/06 01:24
闭包:一个包含有环境变量取值的函数对象。环境变量取值被保存在函数对象的__closure__属性中。
示例:
def line_conf(a, b): def line(x): return ax + b return lineline1 = line_conf(1, 1)line2 = line_conf(4, 5)print(line1(5), line2(5))
这个例子中,函数line与环境变量a,b构成闭包。在创建闭包的时候,我们通过line_conf 的参数a,b说明了这两个环境变量的取值,这样,我们就确定了函数的最终形式(y = x + 1和y = 4x + 5)。我们只需要变换参数a,b,就可以获得不同的直线表达函数。由此,我们可以看到,闭包也具有提高代码可复用性的作用。
装饰器可以对一个函数方法或进行加工。
修饰函数:
def decorator(F): def new_F(a, b): print("input", a, b) return F(a, b) return new_F# get square sum@decoratordef square_sum(a, b): return a**2 + b**2# get square diff@decoratordef square_diff(a, b): return a**2 - b**2print(square_sum(3, 4))print(square_diff(3, 4))
该语法将要装饰的函数作为decorator的参数,在其中定义新函数,添加功能并将其最为对象返回。
@decorator相当与如下代码:square_sum = decorator(square_sum)square_sum(3, 4)
装饰类:
def decorator(aClass): class newClass: def __init__(self, age): self.total_display = 0 self.wrapped = aClass(age) def display(self): self.total_display += 1 print("total display", self.total_display) self.wrapped.display() return newClass@decoratorclass Bird: def __init__(self, age): self.age = age def display(self): print("My age is",self.age)eagleLord = Bird(5)for i in range(3): eagleLord.display()
该语法将要装饰的类作为decorator的参数,在其中定义新类,添加功能并将其最为新类返回。
0 0
- python闭包,装饰器
- python 闭包&装饰器
- python--闭包,装饰器
- python 嵌套函数、闭包装饰器、装饰器例子
- python的闭包和装饰器
- python装饰器和闭包
- Python 的闭包和装饰器
- Python 进阶_闭包 & 装饰器
- Python闭包与装饰器
- python中的闭包与装饰器
- python的闭包及装饰器
- Python 闭包与装饰器
- python闭包函数和装饰器
- python闭包和装饰器
- Python的闭包和装饰器
- Python闭包与装饰器总结
- python闭包和装饰器
- python 装饰器和闭包
- CSS+DIV实现鼠标经过背景变色 [onmouseover; onmouseout]
- UK 更新惊魂记
- android简单的图片适配
- 多继承与虚拟继承
- 150725培训心得(vector)
- python闭包,装饰器
- hdu 5289 单调队列
- Timer的用法
- Handler1
- 学习Spark:一.Spark简介
- BIND97安装配置
- jquery的ajax同步和异步
- HTML-块级元素和内联元素
- hdu 2156 分数矩阵