python decorator 修饰器

decorator 就是给函数加一层皮,好用!

 

 1 from time import ctime
 2 
 3 def deco(func):
 4     def wrappedFunc(*args, **kwargs):
 5         print '[%s] %s called' % (ctime(), func.__name__)
 6         ret = func(*args, **kwargs)
 7         print '[%s] %s call end' % (ctime(), func.__name__)
 8         return ret
 9 
10     return wrappedFunc
11 
12 @deco
13 def foo(a=0,b=1):
14     print "foo's here!"
15     return a,b
16 
17 
18 def main():
19     print foo(3,2)
20 
21 
22 if __name__ == '__main__':
23     main()

在 12 行加上 @deco 相当于定义好 foo 函数之后执行一下 foo = deco(foo)

@deco
def foo(a=0,b=1):
    print "foo's here!"
    return a,b

等价于

def foo(a=0,b=1):
    print "foo's here!"
    return a,b

foo = deco(foo)

  

输出:

[Sun Nov 22 22:14:19 2015] foo called
foo's here!
[Sun Nov 22 22:14:19 2015] foo call end
(3, 2)

 

带参数的修饰器

1 def deco_with_params(a, b, c):
2     def real_deco(func):
3         def wrappedFunc(*args, **kwargs):
4             ret = func(*args, **kwargs)
5             return ret
6         return wrappedFunc
7     return real_deco

 

 

开心玩耍吧!

 

posted on 2015-11-22 22:32  明天有风吹  阅读(202)  评论(0编辑  收藏  举报

导航

+V atob('d2h5X251bGw=')

请备注:from博客园