python 函数装饰器
2014-12-13 20:48
435 查看
函数装饰器提供了一种方式,替函数明确了特定的运算模式,也就是将函数包裹了另一层,在另一函数的逻辑内实现
静态方法的实现可以用如下的装饰器语法编写
class C:
@staticmethod
def meth():
........
def __init__(self,func):
self.calls=0
self.func=func
#----------------------------------------------------------------------
def __call__(self,*args):
"""
__call__"""
self.calls+=1
print 'calls %s to %s ' % (self.calls,self.func.__name__)
self.func(*args)
@tracer
def spam(a,b,c):
print a,b,c
spam(1,2,3)
spam('q','b','c')
spam(4,6,5)
执行结果:
calls 1 to spam
1 2 3
calls 2 to spam
q b c
calls 3 to spam
4 6 5
静态方法的实现可以用如下的装饰器语法编写
class C:
@staticmethod
def meth():
........
装饰器实现的例子:
class tracer:def __init__(self,func):
self.calls=0
self.func=func
#----------------------------------------------------------------------
def __call__(self,*args):
"""
__call__"""
self.calls+=1
print 'calls %s to %s ' % (self.calls,self.func.__name__)
self.func(*args)
@tracer
def spam(a,b,c):
print a,b,c
spam(1,2,3)
spam('q','b','c')
spam(4,6,5)
执行结果:
calls 1 to spam
1 2 3
calls 2 to spam
q b c
calls 3 to spam
4 6 5
相关文章推荐
- Python的函数机制与装饰器实现
- python 装饰器功能以及函数参数使用
- python通过装饰器检查函数参数数据类型的方法
- python 装饰器 二 (装饰带参数的函数)
- python深入笔记--装饰函数
- Python的函数和方法装饰漫谈(Function decorator)
- python: 从函数了解到装饰器
- Python中的函数、装饰器
- Python的函数式编程-传入函数、排序算法、函数作为返回值、匿名函数、偏函数、装饰器
- 【Python】[函数式编程]高阶函数,返回函数,装饰器,偏函数
- python 装饰器功能以及函数参数使用介绍
- 使用装饰器为Python函数做缓存
- python 使用函数装饰器的例子
- python通过装饰器检查函数参数数据类型的方法
- python 函数装饰器学习
- python 装饰器功能以及函数参数使用介绍
- Python 函数装饰器探讨
- Python: 无参数的函数装饰器
- Python函数小结(2)-- 装饰器、 lambda
- Python函数:装饰器