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

python 装饰器

时间:2019-04-19 01:26:48      阅读:153      评论:0      收藏:0      [点我收藏+]

标签:sleep   修改   imp   time()   def   his   name   例子   outer   

实现装饰器知识储备
1、函数既“变量”
2、高阶函数
a:把一个函数名当做实参传给另一个函数(在不修改被装饰函数源代码的情况下为其添加功能)

b:返回值包含函数名(不能修改函数的调用方式)
3、嵌套函数

高阶函数+嵌套函数 =》 装饰器

 

 

 

 

例子:

# -*- coding:utf-8 -*-
# Author:Jason

import time

def timer(func): #普通装饰器
def deco(*args,**kwargs):
start_time = time.time()
func(*args,**kwargs)
stop_time = time.time()
print("the func run time is %s" %(stop_time-start_time))
return deco

 

@timer # @timer 等同于简写 test1 = timer(test1)
def test1():
time.sleep(1)
print(‘this is test1‘)

@timer
def test2(name):
print(‘test2:%s‘%(name))

 

test1()
test2(‘jason‘)

 

 


例子2:

# -*- coding:utf-8 -*-
# Author:Jason

import time

def auth(auth_type): #第一层可以获取判断你参数
def outer_wrapper(fun): #普通装饰器
def doce(*args,**kwargs):
print(‘%s‘%(auth_type))
fun(*args,**kwargs)

return doce
return outer_wrapper

 


@auth(‘local‘)
def test1():
print(‘this is a test1‘)

@auth(‘www‘)
def test2(one1,two1):
print(‘this is a %s and %s‘%(one1,two1))


test1()
test2(23,‘ll‘)

 

python 装饰器

标签:sleep   修改   imp   time()   def   his   name   例子   outer   

原文地址:https://www.cnblogs.com/jasonLiu2018/p/10733395.html

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