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之装饰器的更多相关文章

  1. Python各式装饰器

    Python装饰器,分两部分,一是装饰器本身的定义,一是被装饰器对象的定义. 一.函数式装饰器:装饰器本身是一个函数. 1.装饰函数:被装饰对象是一个函数 [1]装饰器无参数: a.被装饰对象无参数: ...

  2. Python札记 -- 装饰器补充

    本随笔是对Python札记 -- 装饰器的一些补充. 使用装饰器的时候,被装饰函数的一些属性会丢失,比如如下代码: #!/usr/bin/env python def deco(func): def ...

  3. python基础——装饰器

    python基础——装饰器 由于函数也是一个对象,而且函数对象可以被赋值给变量,所以,通过变量也能调用该函数. >>> def now(): ... print('2015-3-25 ...

  4. 【转】详解Python的装饰器

    原文链接:http://python.jobbole.com/86717/ Python中的装饰器是你进入Python大门的一道坎,不管你跨不跨过去它都在那里. 为什么需要装饰器 我们假设你的程序实现 ...

  5. 两个实用的Python的装饰器

    两个实用的Python的装饰器 超时函数 这个函数的作用在于可以给任意可能会hang住的函数添加超时功能,这个功能在编写外部API调用 .网络爬虫.数据库查询的时候特别有用 timeout装饰器的代码 ...

  6. python 基础——装饰器

    python 的装饰器,其实用到了以下几个语言特点: 1. 一切皆对象 2. 函数可以嵌套定义 3. 闭包,可以延长变量作用域 4. *args 和 **kwargs 可变参数 第1点,一切皆对象,包 ...

  7. 理解Python中的装饰器//这篇文章将python的装饰器来龙去脉说的很清楚,故转过来存档

    转自:http://www.cnblogs.com/rollenholt/archive/2012/05/02/2479833.html 这篇文章将python的装饰器来龙去脉说的很清楚,故转过来存档 ...

  8. python基础—装饰器

    python基础-装饰器 定义:一个函数,可以接受一个函数作为参数,对该函数进行一些包装,不改变函数的本身. def foo(): return 123 a=foo(); b=foo; print(a ...

  9. 详解Python的装饰器

    Python中的装饰器是你进入Python大门的一道坎,不管你跨不跨过去它都在那里. 为什么需要装饰器 我们假设你的程序实现了say_hello()和say_goodbye()两个函数. def sa ...

  10. 关于python的装饰器(初解)

    在python中,装饰器(decorator)是一个主要的函数,在工作中,有了装饰器简直如虎添翼,许多公司面试题也会考装饰器,而装饰器的意思又很难让人理解. python中,装饰器是一个帮函数动态增加 ...

随机推荐

  1. [題解]luogu_P1854 花店櫥窗佈置

    來源:題解 一開始看不懂題目,一萬年了終於看懂 f [ i ] [ j ] 表示第i朵花放在第j個花瓶中最大美學值,(花是必須用完嗎?) 顯然放i-1朵花至少要放到前i-1個瓶子里,最多放到前j-1個 ...

  2. GYM 101673G(dp)

    dp[i][j][0/1]:第i天处于第j状态要不要吃. const int maxn = 1e2 + 5; int n, a[maxn], b[maxn]; int dp[maxn][maxn][2 ...

  3. Vue初始化

    Vue上面的函数怎么来的 vue的打包路径 在web中使用的vue打包路径: npm run build 打包生成vue.js 下面是依次引入: src/platforms/web/entry-run ...

  4. 云服务中IaaS、PaaS、SaaS的区别

    越来越多的软件,开始采用云服务. 云服务只是一个统称,可以分成三大类. IaaS:基础设施服务,Infrastructure-as-a-service PaaS:平台服务,Platform-as-a- ...

  5. 简单的UDP程序

    接受端: package com.dcz.udp; import java.io.IOException; import java.net.DatagramPacket; import java.ne ...

  6. 爬虫的两种解析方式 xpath和bs4

    1.xpath解析 from lxml import etree 两种方式使用:将html文档变成一个对象,然后调用对象的方法去查找指定的节点 (1)本地文件 tree = etree.parse(文 ...

  7. 从零开始利用vue-cli搭建简单音乐网站(二)

    1.利用vue-router实现页面跳转 程序可以正常运行之后,下面我们需要配置路由实现页面的局部刷新,这一功能将用来实现网站页面的跳转. 打开程序目录,进入"src\router\inde ...

  8. Visual Studio使用技巧学习

      F7:  代码窗口 Shift+F7:   对象窗口 F4:  属性窗口 闪电图标:    对象的事件 F5:   编译及运行 Ctrl+F5:  编译及运行(不调试) svm+两次Tab:  s ...

  9. openssl 安装配置

    Openssl是个为网络通信提供安全及数据完整性的一种安全协议,囊括了主要的密码算法.常用的密钥和证书封装管理功能以及SSL协议,并提供了丰富的应用程序供测试或其它目的使用.首先下载Openssl包: ...

  10. 1、Centos7 python2.7和yum完全卸载及重装

    完全重装python和yum 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 1.删除现有Python ...