Python 装饰器Decorator(二)】的更多相关文章

对于上一篇“”Python闭包“”随笔中提到的make_averager()函数的如下实现,我们把历史值保存在列表里,每次计算平均值都需要重新求和,当历史值较多时,需要占用比较多的空间并且效率也不高. >>> def make_averager(): ... series = [] ... def averager(new_value): ... series.append(new_value) ... total = sum(series) ... return total/len(s…
装饰器(decorator) 作者:Vamei 出处:http://www.cnblogs.com/vamei 欢迎转载,也请保留这段声明.谢谢! 装饰器(decorator)是一种高级Python语法.装饰器可以对一个函数.方法或者类进行加工.在Python中,我们有多种方法对函数和类进行加工,比如在Python闭包中,我们见到函数对象作为某一个函数的返回结果.相对于其它方式,装饰器语法简单,代码可读性高.因此,装饰器在Python项目中有广泛的应用. 装饰器最早在Python 2.5中出现,…
装饰器 装饰器实质是一个函数,其作用就是在不改动其它函数代码的情况下,增加一些功能.如果我们需要打印函数调用前后日志,可以这么做 def log(func): print('%s is running' % func.__name__) func() def bar(): print('bar') #将bar作为函数log参数传入 >>>log(bar) bar is running bar 这样写下来一个函数打印一个函数的日志是没有问题的,但是很多呢? def log(func) de…
(一) 装饰器基础知识 什么是Python装饰器?Python里装饰器是一个可调用的对象(函数),其参数是另一个函数(被装饰的函数) 假如有一个名字为somedecorator的装饰器,target是被装饰的函数: >>> @somedecorator ... def target(): ... print("running target") 上面代码的效果和下面的书写一样: >>> target = somedecorator(target) @s…
Python有许多出色的语言特性,装饰器(Decorator)便是其中一朵奇葩.先来看看一段代码: def deco1(f): print 'decorate 1' return f def deco2(f): print 'decorate 2' return f @deco1@deco2 def foo(): return 'hello' 保存并执行上面的代码,你会看到如下输出: decorate 2 decorate 1 函数foo没有被调用,但是deco1,deco2被按照一个顺序被调用…
接上篇python 闭包&装饰器(一) 一.功能函数加参数:实现一个可以接收任意数据的加法器 源代码如下: def show_time(f): def inner(*x, **y): # 形参 start = time.time() f(*x, **y) # 相当于add() end = time.time() print('spend %s' % (end - start)) return inner @show_time # @show_time 等于 add = show_time(add…
有参装饰器 def outer(flag): def timer(func): def inner(*args,**kwargs): if flag: print('''执行函数之前要做的''') re = func(*args,**kwargs) if flag: print('''执行函数之后要做的''') return re return inner return timer @outer(False) def func(): print(111) func() 多个装饰器装饰同一个函数…
变量作用域规则 在示例 7-4 中,我们定义并测试了一个函数,它读取两个变量的值:一个是局部变量 a,是函数的参数:另一个是变量 b,这个函数没有定义它. >>> def f1(a): ... print(a) ... print(b) ... >>> f1(3) 3 Traceback (most recent call last): File "<stdin>", line 1, in <module> File &quo…
一 装饰器decorator decorator设计模式允许动态地对现有的对象或函数包装以至于修改现有的职责和行为,简单地讲用来动态地扩展现有的功能.其实也就是其他语言中的AOP的概念,将对象或函数的真正功能也其他辅助的功能的分离. 二Python中的decorator python中的decorator通常为输入一个函数,经过装饰后返回另一个函数.  比较常用的功能一般使用decorator来实现,例如python自带的staticmethod和classmethod. 装饰器有两种形式: @…
此系列文档: 1. 我终于弄懂了Python的装饰器(一) 2. 我终于弄懂了Python的装饰器(二) 3. 我终于弄懂了Python的装饰器(三) 4. 我终于弄懂了Python的装饰器(四) 二.装饰器的高级用法 将参数传递给装饰函数 #它不是黑魔法,只是给包装(wrapper)传递参数: def a_decorator_passing_arguments(function_to_decorate): def a_wrapper_accepting_arguments(arg1, arg2…