装饰器

不改变源代码,也不改变调用方式.

1,在被装饰函数的正上方,写一个@名字。把下面的名字,当作参数。

2,独占一行

@名字

index=名字(index)

import time

@timmer     #index=timmer(index)
def index():
	time.sleep(3)
	print('welcome to oldboy')

index()

#timmer的返回值,赋值给index 。
#index=timmer(index)

装饰器分成2种

1,无参装饰器

2,有参装饰器

装饰器的语法

#无参装饰器
@func #index=func(index)
def index(): pass

index=func(index)
index()

 #有参装饰器:函数的正常调@func(args) 

 

 def index(args):    #@res  #index=res(index)
      pass

index()

  

 

def func(f):
     def wrapper(*args,**kwargs):

       res=f(*args,**kwargs)
       return res

    return wrapper

  

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

  

posted @ 2018-01-16 11:47  老王的农场  阅读(88)  评论(0编辑  收藏  举报