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

 

 

开心玩耍吧!

 

相关文章:

  • 2022-12-23
  • 2018-05-12
  • 2022-01-13
  • 2021-07-14
  • 2021-12-14
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-10-06
  • 2022-12-23
  • 2018-05-01
  • 2021-09-19
  • 2022-02-20
  • 2021-05-09
相关资源
相似解决方案