python学习day4之路
装饰器(http://egon09.blog.51cto.com/9161406/1836763)
1、装饰器:本质是函数;
装饰器(装饰其他函数),就是为其他函数添加附加功能;
原则:1.不能修改被装饰函数的源代码;
2.不能修改被装饰的函数的调用方式;
装饰器对被装饰的函数完全透明的,没有修改被装饰函数的代码和调用方式。
实现装饰器知识储备:
1.函数即“变量”;
2.高阶函数;
3.嵌套函数
高阶函数+嵌套函数=》装饰器
匿名函数(lambda表达式)
>>> calc = lambda x:x*3
>>> calc(2)
6
高阶函数:
a.把一个函数名当做实参传递给另外一个函数;
>>> def bar():
print("in the bar.....")
>>> def foo(func):
print(func)
>>> foo(bar)
<function bar at 0x7f8b3653cbf8>
b.返回值中包含函数名;
>>> import time
>>> def foo():
time.sleep(3)
print("in the foo.....")
>>> def main(func):
print(func)
return func
>>> t = main(foo)
<function foo at 0x7fb7dc9e3378>
>>> t()
in the foo.....
装饰器:
在不修改源代码的情况下,统计程序运行的时间:
import time def timmer(func):
def warpper(*args,**kwargs): #warpper(*args,**kwargs)万能参数,可以指定参数,也可以不指定参数
start_time = time.time() #计算时间
func()
stop_time = time.time()
print("the func run time is %s" %(stop_time-start_time)) #计算函数的运行时间
return warpper @timmer #等价于test1 = timmer(test1),因此函数的执行调用是在装饰器里面执行调用的
def test1():
time.sleep(3)
print("in the test1") test1()
运行结果如下:
in the test1
the func run time is 3.001983404159546
装饰器带参数的情况:
import time def timmer(func):
def warpper(*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 warpper #返回内层函数名 @timmer
def test1():
time.sleep(3)
print("in the test1") @timmer #test2 = timmer(test2)
def test2(name):
print("in the test2 %s" %name) test1()
test2("alex")
运行结果如下:
in the test1
the func run time is 3.0032410621643066
in the test2 alex
the func run time is 2.3603439331054688e-05
装饰器返回值情况:
import time
user,passwd = "alex","abc123" def auth(func):
def wrapper(*args,**kwargs):
username = input("Username:").strip()
password = input("Password:").strip() if user == username and passwd == password:
print("\033[32;1mUser has passed authentication.\033[0m")
return func(*args,**kwargs) #实际上执行调用的函数
# res = func(*args,**kwargs)
# return res #函数返回值的情况,因为装饰器调用的时候是在装饰器调用的函数,因此返回值也在这个函数中
else:
exit("\033[31;1mInvalid username or password.\033[0m")
return wrapper def index():
print("welcome to index page...") @auth
def home():
#用户自己页面
print("welcome to home page...")
return "form home..." @auth
def bbs():
print("welcome to bbs page") index()
print(home())
bbs()
装饰器带参数的情况:
实现:1、本地验证;2、远程验证
import time
user,passwd = "alex","abc123" def auth(auth_type):
'''函数的多层嵌套,先执行外层函数'''
print("auth_type",auth_type)
def out_wrapper(func):
def wrapper(*args,**kwargs):
print("wrapper func args:",*args,**kwargs)
if auth_type == "local":
username = input("Username:").strip()
password = input("Password:").strip() if user == username and passwd == password:
print("\033[32;1mUser has passed authentication.\033[0m")
func(*args,**kwargs) #实际上执行调用的函数
# res = func(*args,**kwargs)
# return res #函数返回值的情况,因为装饰器调用的时候是在装饰器调用的函数,因此返回值也在这个函数中
else:
exit("\033[31;1mInvalid username or password.\033[0m")
elif auth_type == "ldap":
print("搞毛线lbap,傻逼....")
return wrapper
return out_wrapper def index():
print("welcome to index page...") @auth(auth_type="local")
def home():
#用户自己页面
print("welcome to home page...")
return "form home..." @auth(auth_type="ldap")
def bbs():
print("welcome to bbs page") index()
home()
bbs() #函数没有,因为没有调用函数,函数的调用在装饰器里面,是装饰器调用了函数
迭代器和生成器
生成器
通过列表生成式,我们可以直接创建一个列表。但是,受到内存限制,列表容量肯定是有限的。而且,创建一个包含100万个元素的列表,不仅占用很大的存储空间,如果我们仅仅需要访问前面几个元素,那后面绝大多数元素占用的空间都白白浪费了。
所以,如果列表元素可以按照某种算法推算出来,那我们是否可以在循环的过程中不断推算出后续的元素呢?这样就不必创建完整的list,从而节省大量的空间。在Python中,这种一边循环一边计算的机制,称为生成器:generator。
>>> l1 = (i for i in range(10))
>>> l1
<generator object <genexpr> at 0x7f6a9fbcaeb8>
>>> l1.__next__()
0
>>> l1.__next__()
1
生成器:只有在调用时才会生成相应的数据;
只有通过__next__()方法进行执行,这种能够记录程序运行的状态,yield用来生成迭代器函数。(只能往后调用,不能向前或者往后推移,只记住当前状态,因此银行的系统用来记录的时候可以使用yield函数)。
'''利用yield实现异步的效果,发送接收消息'''
import time def consumer(name):
'''消费者吃包子模型'''
print("%s准备吃包子了......" %name)
while True:
'''循环,由于没有终止'''
baozi = yield
print("包子%s被%s吃了......" %(baozi,name)) def producer(boss):
'''生产者生产包子模型,生产者要生产包子'''
c1 = consumer("A")
c2 = consumer("B")
c1.__next__()
c2.__next__()
'''接下来,生产者要生产包子了,并传递给消费者'''
for i in range(,):
time.sleep()
c1.send(i)
c2.send(i) producer("Alex") 运行如下:
A准备吃包子了......
B准备吃包子了......
包子1被A吃了......
包子1被B吃了......
包子2被A吃了......
包子2被B吃了......
包子3被A吃了......
包子3被B吃了......
包子4被A吃了......
包子4被B吃了......
包子5被A吃了......
包子5被B吃了......
包子6被A吃了......
包子6被B吃了......
包子7被A吃了......
包子7被B吃了......
包子8被A吃了......
包子8被B吃了......
包子9被A吃了......
包子9被B吃了.....
迭代器
我们已经知道,可以直接作用于for循环的数据类型有以下几种:
一类是集合数据类型,如list、tuple、dict、set、str等;
一类是generator,包括生成器和带yield的generator function。
这些可以直接作用于for循环的对象统称为可迭代对象:Iterable。
可以使用isinstance()判断一个对象是否是Iterable对象
>>> from collections import Iterable>>> isinstance([], Iterable)True>>> isinstance({}, Iterable)True>>> isinstance('abc', Iterable)True>>> isinstance((x for x in range(10)), Iterable)True>>> isinstance(100, Iterable)Falsepython学习day4之路的更多相关文章
- python学习day4之路文件的序列化和反序列化
json和pickle序列化和反序列化 json是用来实现不同程序之间的文件交互,由于不同程序之间需要进行文件信息交互,由于用python写的代码可能要与其他语言写的代码进行数据传输,json支持所有 ...
- python学习day4软件目录结构规范
为什么要设计好目录结构? 参考:http://www.cnblogs.com/alex3714/articles/5765046.html "设计项目目录结构",就和"代 ...
- Python学习-day4
学习装饰器,首先听haifeng老师讲解了一下准备知识. 1.函数即变量 2.高阶函数+嵌套函数==>装饰器 装饰器的作用是在,1)不改变源代码,2)不改变原函数的调用方式的前提下为函数增加新的 ...
- Python学习day4 数据类型Ⅱ(列表,元祖)
day4 知识补充&数据类型:列表,元祖 1.知识补充 1.编译型/解释型 编译型:在代码编写完成之后编译器将其变成另外一个文件教给你算计执行. 代表语言:Java,c,c++ ,c#, Go ...
- python学习day4 数据类型 if语句
1.变量的内存管理 cpython解释器垃圾回收机制 什么是垃圾,当一个值身上没有绑定变量名时,(该值的引用计数=0时)就是一个垃圾 age=18 #18的引用计数=1 x=age #18的引用计数 ...
- python学习day4
目录 一.迭代器 二.yield生成器 三.装饰器 四.递归 五.基础算法 迭代器 #1.在不使用for循环的情况下 li = [11 ,22, 33, 44] #count = len(li) #s ...
- python学习Day4 流程控制(if分支,while循环,for循环)
复习 1.变量名命名规范 -- 1.只能由数字.字母 及 _ 组成 -- 2.不能以数字开头 -- 3.不能与系统关键字重名 -- 4._开头有特殊含义 -- 5.__开头__结尾的变量,魔法变量 - ...
- python学习 day4 (3月5日)---列表
列表: 容器性数据 有序 可更改 大量数据 一.增 1.追加 append(objcet) 2.索引增加 Insert(index,元素) 3.迭代追加 extend(object) ...
- python学习之路-day2-pyth基础2
一. 模块初识 Python的强大之处在于他有非常丰富和强大的标准库和第三方库,第三方库存放位置:site-packages sys模块简介 导入模块 import sys 3 sys模 ...
随机推荐
- kibana做图表无法选取需要选的字段
kibana做图表无法选取需要选的字段,即通过term的方式过滤选择某一个field时发现列表里无此选项. 再去discover里看,发现此字段前面带有问号,点击后提示这个字段未做索引,不能用于vis ...
- linq的语法和案例
本篇逐一介绍linq各个关键字的用法(from,select,group,into等),本篇所有的案例都是用linqpad来完成的(官方地址:http://www.linqpad.net/),建议想学 ...
- PHP常见数组方法和函数
current();当前游标指向的数组单元值 next();下一个数组单元值 end()最后一个 reset()复位 prev()把数组指针往前一位 写法:$arr=array('a','b','c' ...
- 将输出语句打印至tomcat日志文件中
tomcat-9.0.0 将程序中 System.out.println("------------这是输出语句System.out.println()-------- ...
- 51nod 1103 N的倍数 (鸽巢原理)
1103 N的倍数 题目来源: Ural 1302 基准时间限制:1 秒 空间限制:131072 KB 分值: 40 难度:4级算法题 收藏 关注 一个长度为N的数组A,从A中选出若干个数,使得这 ...
- Android 利用广播接收器启动服务
public class MainActivity extends Activity { private Button bt ; protected void onCreate(Bundle save ...
- 【学习笔记】初识FreeMarker简单使用
楔子: 之前在和同事讨论,同事说“jsp技术太古老了,有几种页面技术代替,比如FreeMarker.Velocity.thymeleaf,jsp快废弃了……”云云.我这一听有点心虚……我在后端部分越刨 ...
- Elasticsearch技术解析与实战(三)文档的聚合
1.计算每个tag下的商品数量 PUT /database/_mapping/product { "properties": { "tags": { " ...
- easy-animation | Animation for Sass
最近因为项目缘故,勾搭上了Sass. 其实在折腾Sass之前,也有简单用过一下Less.但碍于Less提供的一些API实在让人觉得有点多余,用着就是不顺手,最后就不了了之啦. Sass之所以用起来舒服 ...
- LintCode 58: Compare Strings
LintCode 58: Compare Strings 题目描述 比较两个字符串A和B,确定A中是否包含B中所有的字符.字符串A和B中的字符都是大写字母. 样例 给出A = "ABCD&q ...