码迷,mamicode.com
首页 > 编程语言 > 详细

Python装饰器详解

时间:2017-06-11 12:54:54      阅读:224      评论:0      收藏:0      [点我收藏+]

标签:nbsp   函数调用   pytho   inner   size   out   规则   logs   return   

首先是不使用装饰器的情况,又需要在不修改原函数的情况话修改函数结果

 1 def outer(func):
 2     def inner():
 3         print("Hello")
 4         ret = func()
 5         print("World")
 6         return ret
 7     return inner
 8 
 9 def Fun():
10     print("Fun")
11 
12 outer(Fun)()
13 
14 结果:
15 Hello
16 Fun
17 World

  在不使用装饰器的情况下,虽然结果一样,但是调用者需要修改调用方式,如果该函数是提供给很多人使用的,则很不方便

接下来是使用装饰器的方法

 1 def outer(func):
 2     def inner():
 3         print("Hello")
 4         ret = func()
 5         print("World")
 6         return ret
 7     return inner
 8 
 9 @outer
10 def Fun():
11     print("Fun")
12 
13 Fun()

结果相同,但是函数调用者不需要修改调用方式

 

函数带有参数的情况

 1 def outer(func):
 2     def inner(x, y):
 3         print("Hello")
 4         ret = func(x, y)
 5         print("World")
 6         return ret
 7     return inner
 8 
 9 @outer
10 def Fun(x, y):
11     print(x + y)
12 
13 Fun(1, 2)
14 
15 结果:
16 Hello
17 3
18 World

 

但是如果该装饰器需要装饰多个函数,并且函数中的参数个数不同,则可以采用下列方法解决

 1 def outer(func):
 2     def inner(*args, **kwargs):
 3         print("Hello")
 4         ret = func(*args, **kwargs)
 5         print("World")
 6         return ret
 7     return inner
 8 
 9 @outer
10 def Fun1(x, y):
11     print(x + y)
12 
13 @outer
14 def Fun2(x, y, z):
15     print(x + y + z)
16 
17 Fun1(1, 2)
18 Fun2(2, 3, 4)

  在这种情况下,多个不同函数也可以使用同一个装饰器,并且python内部自动分配参数。

 

多个装饰器同时装饰一个函数

  之前我们的装饰器是在函数调用前后分别输出 <q>Hello World</q> ,现在我们添加一个新的需求,在输出Hello之前输出Python用过重新写另外一个装饰器也可以实现,但是比较麻烦,不符合编码的代码重用规则,在这里我们使用另外一个装饰器,只需要将新增的功能添加到装饰器即可。

 

 1 def outer(func):
 2     def inner(*args, **kwargs):
 3         print("Hello")
 4         ret = func(*args, **kwargs)
 5         print("World")
 6         return ret
 7     return inner
 8 
 9 def outer2(func):
10     def inner(*args, **kwargs):
11         print("python")
12         ret = func(*args, **kwargs)
13         return ret
14     return inner
15 
16 #使用两个装饰器
17 @outer2
18 @outer
19 def Fun(x, y):
20     print(x + y)
21 
22 Fun(1, 2)

 

Python装饰器详解

标签:nbsp   函数调用   pytho   inner   size   out   规则   logs   return   

原文地址:http://www.cnblogs.com/xhcdream/p/6984714.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!