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中,装饰器是一个帮函数动态增加 ...
随机推荐
- mysql状态查询
在监控中,都是去探测这些状态数据,然后换算到时间刻度上,像zabbix. show status like 'uptime'; --查看select语句的执行数 show [global] statu ...
- 旧版本linaro-ubuntu更改软件源
最近打算研究下arm版本的linaro ubuntu桌面系统,但是在安装软件时速度实在太慢,便想修改一下软件源. 无奈查看系统版本时,显示的是linaro 11.12,但却不知和ubuntu有和关系, ...
- C# 可空类型(Nullable)
C# 提供了一个特殊的数据类型,nullable 类型(可空类型),可空类型可以表示其基础值类型正常范围内的值,再加上一个 null 值. 例如,Nullable< Int32 >,读作& ...
- Java之内部类、包及代码块
个人通俗理解: 1.内部类:有点类似于写在父类中的子类,根据位置不一样为不同的名字,和相应的访问方式不同:不过要访问外部类的话,需要充分运用好this(本类)的这个关键字:要是需要快速的创建子类对象的 ...
- 12.JAVA-基本数据类型的包装类操作
1.基本数据类型的包装类 java是一个面向对象编程语言,也就是说一切操作都要用对象的形式进行.但是有个矛盾: 基本数据类型(char,int,double等)不具备对象特性(不携带属性和方法) 这样 ...
- 前端开发神器 - Brackets
做了几年的 .Net 项目开发,后来公司转 Java 语言开发,Java 做了还没一年,公司准备前后端分离开发,而我被分到前端! Brackets是一款基于web(html+css+js)开发的web ...
- [windows]win7设置wifi热点
1.启用并设定虚拟WiFi网卡:netsh wlan set hostednetwork mode=allow ssid=whylaughing key=124025621 2.开启无线wifi网络: ...
- jmeter中文件上传配置
- 洛谷 First Step (ファーストステップ) 3月月赛T1
题目背景 知らないことばかりなにもかもが(どうしたらいいの?) 一切的一切 尽是充满了未知数(该如何是好) それでも期待で足が軽いよ(ジャンプだ!) 但我仍因满怀期待而步伐轻盈(起跳吧!) 温度差なん ...
- 解决Starting to watch source with Jekyll and Compass. Starting Rack on port 4000
问题 Starting to watch source with Jekyll and Compass. Starting Rack on port 4000 rake aborted! Errno: ...