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中,装饰器是一个帮函数动态增加 ...
随机推荐
- C# 面向对象之面向接口
接口的定义 与类不同的是接口用interface关键字 (1)接口中所有成员不能添加任何修饰符,默认为public,如果显示指定修饰符将会出现编译错误; (2)接口中不能包含字段.运算符重载.实例构造 ...
- [软件工程基础]2017.10.27 第二次 Scrum 会议
决议 周六前项目交接 Milestone 完成 周六集体开发 游心整理物理网站上的实验流程和绪论复习题 石奇川上线静态版实验流程和绪论复习题库 李煦通构思后端如何实现绪论题库,包括和用户记录的关联方式 ...
- python入门之实例-商品选择
需求: 显示一系列商品,根据序号选择商品 li = ["手机","电脑","电视"] #函数enumerate在for循环遍历的时候,会默认 ...
- clearfix的运行机制和进化
话说为什么要把这个记下来,因为昨天去面试,问了clearfix的原理,当时脑子不清晰,回答得真是想要咬舌自尽.遂,决定,要搞清楚来龙去脉~~~(资料来自网上博主们,)http://www.aseoe. ...
- [在读]HTML5数据推送应用开发
最近买的,讲SSE的,才看完前2章.
- Redis 数据导入导出,redis-dump命令
安装redis-dump 工具 yum install ruby rubygems ruby-devel# 修改为国内源gem sources --add http://gems.ruby-china ...
- echarts 添加Loading 等待。
capturedsDetailsEcharts: function(id) { if (!id) { id = mini.get("chnNameCaptureds").getVa ...
- 微信小程序---图片上传+服务端接受
原文地址:http://blog.csdn.net/sk719887916/article/details/54312573 微信小程序,图片上传,应用地方-修改用户信息的头像. 详细代码: 小程序的 ...
- 关于js对象中的,属性的增删改查问题
删除主要是delet方法: 1 function Person(){}; 2 var person = new Person(); 3 person.name = 'yy'; 4 person.gen ...
- vs2013编译过程中,错误 59 error C4996: 'GetVersionExW': 被声明为已否决
好几次碰到这个错误,必须mark 一下!!!!!Project Properties > Configuration Properties > C/C++ > General > ...