day20-python之装饰器
1.装饰器
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import time
def cal(l):
start_time=time.time()
res=0
for i in l:
time.sleep(0.1)
res+=i
stop_time = time.time()
print('函数的运行时间是%s' %(stop_time-start_time))
return res print(cal(range(100))) def index():
pass def home():
pass
2.装饰器预演
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import time
def timmer(func):
def wrapper(*args,**kwargs):
start_time=time.time()
res=func(*args,**kwargs)
stop_time = time.time()
print('函数运行时间是%s' %(stop_time-start_time))
return res
return wrapper def timmer1(func):
def wrapper(*args,**kwargs):
start_time = time.time()
res = func(*args,**kwargs)
stop_time = time.time()
print('函数运行时间是%s' %(stop_time-start_time))
return res
return wrapper() @timmer
def cal(l):
res=0
for i in l:
time.sleep(0.1)
res+=i
return res res=cal(range(20))
print(res) def index():
pass def home():
pass
3.高阶函数
#!/usr/bin/env python
# -*- coding:utf-8 -*-
'''
高阶函数定义:
1.函数接收的参数是一个函数名
2.函数的返回值是一个函数名
3.满足上述条件任意一个,都可称之为高阶函数
'''
# import time
# def foo():
# time.sleep(3)
# print('你好啊林师傅') # def test(func):
# # print(func)
# start_time=time.time()
# func()
# stop_time = time.time()
# print('函数运行时间是 %s' % (stop_time-start_time))
# foo()
# test(foo) # def foo():
# print('from the foo')
# def test(func):
# return func
# res=test(foo)
# # print(res)
# res() import time
def foo():
time.sleep(3)
print('来自foo') #不修改foo源代码
#不修改foo调用方式 #多运行了一次,不合格
# def timer(func):
# start_time=time.time()
# func()
# stop_time = time.time()
# print('函数运行时间是 %s' % (stop_time-start_time))
# return func
# foo=timer(foo)
# foo() #没有修改被修饰函数的源代码,也没有修改被修饰函数的调用方式,但是也没有为被修饰函数添加新功能
# def timer(func):
# start_time=time.time()
# return func
# stop_time = time.time()
# print('函数运行时间是 %s' % (stop_time-start_time))
#
# foo=timer(foo)
# foo()
4.函数嵌套
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# def bar():
# print('from bar')
#
# def foo():
# print('from foo')
# def test():
# pass def father(auth_type):
# print('from father %s' %name)
def son():
# name='linhaifeng_1'
# print('我的爸爸是%s' %name)
def grandson():
print('我的爷爷是%s' %auth_type)
grandson()
# print(locals())
son()
# father('linhaifeng')
father('filedb')
5.加上返回值
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import time
def timmer(func): #func=test
def wrapper():
start_time=time.time()
res=func() #就是在运行test()
stop_time = time.time()
print('运行时间是%s' %(stop_time-start_time))
return res
return wrapper @timmer #test=timmer(test)
def test():
time.sleep(3)
print('test函数运行完毕')
return '这是test的返回值' # res=test() #就是在运行wrapper
# print(res)
6.加上参数
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import time
def timmer(func): #func=test1
def wrapper(*args,**kwargs): #test('linhaifeng',age=18) args=('linhaifeng') kwargs={'age':18}
start_time=time.time()
res=func(*args,**kwargs) #就是在运行test() func(*('linhaifeng'),**{'age':18})
stop_time = time.time()
print('运行时间是%s' %(stop_time-start_time))
return res
return wrapper # @timmer #test=timmer(test) def test(name,age):
time.sleep(3)
print('test函数运行完毕,名字是【%s】 年龄是【%s】' %(name,age))
return '这是test的返回值' @timmer
def test1(name,age,gender):
time.sleep(1)
print('test1函数运行完毕,名字是【%s】 年龄是【%s】 性别【%s】' %(name,age,gender))
return '这是test的返回值' res=test('linhaifeng',age=18) #就是在运行wrapper
print(res)
# test1('alex',18,'male') # test1('alex',18,'male') # def test2(name,age,gender): #test2(*('alex',18,'male','x','y'),**{})
# #name,age,gender=('alex',18,'male','x','y')
# print(name)
# print(age)
# print(gender)
#
# def test1(*args,**kwargs):
# test2(*args,**kwargs) #args=('alex',18,'male','x','y') kwargs={}
#
# # test2('alex',18,gender='male')
#
# test1('alex',18,'male')
7.装饰器实现
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import time
def timmer(func): #func=test
def wrapper():
# print(func)
start_time=time.time()
func() #就是在运行test()
stop_time = time.time()
print('运行时间是%s' %(stop_time-start_time))
return wrapper @timmer #test=timmer(test)
def test():
time.sleep(3)
print('test函数运行完毕')
test() # res=timmer(test) #返回的是wrapper的地址
# res() #执行的是wrapper() # test=timmer(test) #返回的是wrapper的地址
# test() #执行的是wrapper() # @timmer 就相当于 test=timmer(test)
8.验证功能装饰器
#!/usr/bin/env python
# -*- coding:utf-8 -*-
user_list=[
{'name':'alex','passwd':''},
{'name':'linhaifeng','passwd':''},
{'name':'wupeiqi','passwd':''},
{'name':'yuanhao','passwd':''},
]
current_dic={'username':None,'login':False} def auth_func(func):
def wrapper(*args,**kwargs):
if current_dic['username'] and current_dic['login']:
res = func(*args, **kwargs)
return res
username=input('用户名:').strip()
passwd=input('密码:').strip()
for user_dic in user_list:
if username == user_dic['name'] and passwd == user_dic['passwd']:
current_dic['username']=username
current_dic['login']=True
res = func(*args, **kwargs)
return res
else:
print('用户名或者密码错误') return wrapper @auth_func
def index():
print('欢迎来到京东主页') @auth_func
def home(name):
print('欢迎回家%s' %name) @auth_func
def shopping_car(name):
print('%s的购物车里有[%s,%s,%s]' %(name,'奶茶','妹妹','娃娃')) print('before-->',current_dic)
index()
print('after--->',current_dic)
home('产品经理')
shopping_car('产品经理')
10.带参数验证功能装饰器
#!/usr/bin/env python
# -*- coding:utf-8 -*-
user_list=[
{'name':'alex','passwd':''},
{'name':'linhaifeng','passwd':''},
{'name':'wupeiqi','passwd':''},
{'name':'yuanhao','passwd':''},
]
current_dic={'username':None,'login':False} def auth(auth_type='filedb'):
def auth_func(func):
def wrapper(*args,**kwargs):
print('认证类型是',auth_type)
if auth_type == 'filedb':
if current_dic['username'] and current_dic['login']:
res = func(*args, **kwargs)
return res
username=input('用户名:').strip()
passwd=input('密码:').strip()
for user_dic in user_list:
if username == user_dic['name'] and passwd == user_dic['passwd']:
current_dic['username']=username
current_dic['login']=True
res = func(*args, **kwargs)
return res
else:
print('用户名或者密码错误')
elif auth_type == 'ldap':
print('鬼才特么会玩')
res = func(*args, **kwargs)
return res
else:
print('鬼才知道你用的什么认证方式')
res = func(*args, **kwargs)
return res return wrapper
return auth_func @auth(auth_type='filedb') #auth_func=auth(auth_type='filedb')-->@auth_func 附加了一个auth_type --->index=auth_func(index)
def index():
print('欢迎来到京东主页') @auth(auth_type='ldap')
def home(name):
print('欢迎回家%s' %name)
#
@auth(auth_type='sssssss')
def shopping_car(name):
print('%s的购物车里有[%s,%s,%s]' %(name,'奶茶','妹妹','娃娃')) # print('before-->',current_dic)
# index()
print('after--->',current_dic)
home('产品经理')
# shopping_car('产品经理')
day20-python之装饰器的更多相关文章
- Python各式装饰器
Python装饰器,分两部分,一是装饰器本身的定义,一是被装饰器对象的定义. 一.函数式装饰器:装饰器本身是一个函数. 1.装饰函数:被装饰对象是一个函数 [1]装饰器无参数: a.被装饰对象无参数: ...
- Python札记 -- 装饰器补充
本随笔是对Python札记 -- 装饰器的一些补充. 使用装饰器的时候,被装饰函数的一些属性会丢失,比如如下代码: #!/usr/bin/env python def deco(func): def ...
- python基础——装饰器
python基础——装饰器 由于函数也是一个对象,而且函数对象可以被赋值给变量,所以,通过变量也能调用该函数. >>> def now(): ... print('2015-3-25 ...
- 【转】详解Python的装饰器
原文链接:http://python.jobbole.com/86717/ Python中的装饰器是你进入Python大门的一道坎,不管你跨不跨过去它都在那里. 为什么需要装饰器 我们假设你的程序实现 ...
- 两个实用的Python的装饰器
两个实用的Python的装饰器 超时函数 这个函数的作用在于可以给任意可能会hang住的函数添加超时功能,这个功能在编写外部API调用 .网络爬虫.数据库查询的时候特别有用 timeout装饰器的代码 ...
- python 基础——装饰器
python 的装饰器,其实用到了以下几个语言特点: 1. 一切皆对象 2. 函数可以嵌套定义 3. 闭包,可以延长变量作用域 4. *args 和 **kwargs 可变参数 第1点,一切皆对象,包 ...
- 理解Python中的装饰器//这篇文章将python的装饰器来龙去脉说的很清楚,故转过来存档
转自:http://www.cnblogs.com/rollenholt/archive/2012/05/02/2479833.html 这篇文章将python的装饰器来龙去脉说的很清楚,故转过来存档 ...
- python基础—装饰器
python基础-装饰器 定义:一个函数,可以接受一个函数作为参数,对该函数进行一些包装,不改变函数的本身. def foo(): return 123 a=foo(); b=foo; print(a ...
- 详解Python的装饰器
Python中的装饰器是你进入Python大门的一道坎,不管你跨不跨过去它都在那里. 为什么需要装饰器 我们假设你的程序实现了say_hello()和say_goodbye()两个函数. def sa ...
- 关于python的装饰器(初解)
在python中,装饰器(decorator)是一个主要的函数,在工作中,有了装饰器简直如虎添翼,许多公司面试题也会考装饰器,而装饰器的意思又很难让人理解. python中,装饰器是一个帮函数动态增加 ...
随机推荐
- [題解](DP)CF713C_Sonya and Problem Wihtout a Legend
對於不嚴格單調的我們可以n^2DP,首先每個數一定在原數組中出現過,如果沒出現過不如減小到出現過的那個花費更小,效果相同 所以f[i][j]表示把i改到離散化后j的最小代價,每次維護前一狀態最小值mn ...
- ES5(基本包装类型)字符串的方法
看一下字符串有哪些常用的方法: 1.concat();将多个文本组合起来,返回新的字符串,就是拼接字符串. 查找位置 2.indexOf();返回要匹配的字符在字符串第一次出现的索引,参数就是匹配的字 ...
- NodeJs前端构建工具 ——————之Grunt篇
为何使用grunt? 如何搭建grunt? 开始第一个grunt项目 基础()合并js文件 开始第一个grunt项目 基础()压缩js 开始第一个grunt项目 基础()代码规范检测 开始第一个gru ...
- Xenu使用随记
经试验发现,如果配置了host进行网站检测时,Xenu和浏览器一样,都需要配置了host之后,重新打开Xenu程序(浏览器),host的配置才能生效.
- c#学习系列之跳出循环 break,continue
break是完全跳出循环: ) { ) break; Console.WriteLine(a++); } 此处输出1,2,3,4,5,6,7,8 continue是跳出当前的循环: ;i<=;i ...
- HTML <form> 标签的 enctype
form的enctype有三种 application/x-www-form-urlencoded 在发送前编码所有字符(默认) multipart/form-data 不对字符编码. 在使用包含文件 ...
- zoj3765Lights(splay)
链接 splay的增删改操作. 刚开始对于某段区间首先有了lazy标记时,把其左右孩子给交换了,导致在pushup时又交换了一次而debug了n久. #include <iostream> ...
- ItemsControl Grouping分组
ItemsControl属性GroupStyle Grouping再ItemsControl源代码 public class ItemsControl : Control, IAddChild, IG ...
- Spring使用_进阶
概述 本文主要写了几个关于Spring Aware,多线程,计划任务(定时任务),条件注解,组合注解,元注解,Spring测试的小例子以及关于@Enable*注解的工作原理的理解. Spring Aw ...
- Emacs Org-mode中英文字体设置
Emacs Org-mode中英文字体设置 Table of Contents 1. 缺省字体存在的问题 2. 解决方法 2.1. 环境说明 2.2. 思路和方法 2.3. emacs设置代码 2.4 ...