1 from django.utils.decorators import method_decorator
2
3 def outer(func):
4 def inner(*args,**kwargs): #inner接收参数
5 print(args)
6 return func(*args,**kwargs) #将inner得到的参数传给func(),即add(),形参
7 return inner
8
9 @outer
10 def add(b): #接收参数
11 a=3
12 print(a+b)
13 add(9) #传参给inner
14
15
16
17 class aaa():
18 @method_decorator(outer) #在类中使用装饰器
19 def re(self,c):
20 print(c+6)
21
22 @outer
23 def er(self):
24 pass
25
26 a=aaa()
27 a.re(9)
View Code
*args,**kwargs的区别
def function(x,y,*args,**kwargs):
print(type(x))
print(args)
print(kwargs)
print(type(args))
print(type(kwargs))
function(1,2,3,4,5,a=1,b=2,c=3)
<type 'int'>
(3, 4, 5) #*args返回的是数组
{'a': 1, 'c': 3, 'b': 2} #**kwargs返回的字典
<type 'tuple'>
<type 'dict'>
###@wraps:避免被装饰函数自身的信息丢失
----------------------------------
def decorator(func):
def inner_function():
pass
return inner_function
@decorator
def func():
pass
print(func.__name__)
#inner_function
-----------------------------------
from functools import wraps
def decorator(func):
@wraps(func)
def inner_function():
pass
return inner_function
@decorator
def func():
pass
print(func.__name__)
#func
#类装饰器
----------------
class Decorator(object):
def __init__(self, f):
self.f = f
def __call__(self):
print("decorator start")
self.f()
print("decorator end")
@Decorator
def func():
print("func")
func()
'''
decorator start
func
decorator end
'''
import time
def decorator(func):
def wrapper(*args,**kwargs):
start_time = time.time()
func(*args,**kwargs)
end_time = time.time()
print(end_time - start_time)
return wrapper
class Method(object):
@decorator
def func(self):
time.sleep(0.8)
p1 = Method()
p1.func() # 函数调用
'''
0.815999984741
对于类方法来说,都会有一个默认的参数self,它实际表示的是类的一个实例,所以在装饰器的内部函数wrapper也要传入一个参数
- me_instance(任意参数)就表示将类的实例p1传给wrapper,其他的用法都和函数装饰器相同。
'''
#多层装饰器,执行顺序
def X(func):
print('there is X') #1
def inner():
print('there is X inner') #4
func() #5---func()只执行一遍
print('there is X inner later') #6
return inner
def Y(func):
print('there is Y') #2
def inner():
print('there is Y inner') #3
func()
print('there is Y inner later') #7
return inner
@Y #远
@X #近
def dog():
print('you are comming')
dog()
---------
there is X
there is Y
there is Y inner
there is X inner
you are comming
there is X inner later
there is Y inner later