def outer(func):
def inner():
print('hello')
print('hello')
print('hello')
r = func()
print('end')
print('end')
print('end')
return inner
@outer
def f1():
print("f1 called")
# 1:执行outer函数,并且将其下面的函数名(这里就是f1函数),当做参数传递给outer函数
# 2:将outer的返回值重新赋值给f1=outer的返回值
# 3:新f1函数 = inner
# 装饰器的本质就是将原函数封装到一个新函数里,让原函数执行新函数里的内容
f1()

输出结果为:

hello
hello
hello
f1 called
end
end
end

只要函数应用装饰器,那么函数就被重新定义,重新定义为装饰器的内层函数

装饰器含两个参数的函数:

def outer(func):
def inner(a1,a2):
print('')
ret = func(a1,a2)
print('')
return ret
return inner
@outer
def index(a1,a2):
print('')
return a1+a2
index(1,2)

装饰器含N个参数的函数:

def outer(func):
def inner(*arg,**kwargs):
print('begin')
ret = func(*arg,**kwargs)
print('end')
return ret
return inner

多个装饰器装饰同一个函数:

def outer_0(func):
def inner(*arg,**kwargs):
print('top')
ret = func(*arg,**kwargs)
return ret
return inner def outer(func):
def inner(*arg,**kwargs):
print('begin')
ret = func(*arg,**kwargs)
print('end')
return ret
return inner @outer_0
@outer
def index(a1,a2):
print('index')
return a1+a2
index(1,2)

迭代器

迭代器是访问集合元素的一种方式。迭代器对象从集合的第一个元素开始访问,直到所有的元素被访问完结束。迭代器只能往前不会后退,不过这也没什么,因为人们很少在迭代途中往后退。另外,迭代器的一大优点是不要求事先准备好整个迭代过程中所有的元素。迭代器仅仅在迭代到某个元素时才计算该元素,而在这之前或之后,元素可以不存在或者被销毁。这个特点使得它特别适合用于遍历一些巨大的或是无限的集合,比如几个G的文件

特点:

  1. 访问者不需要关心迭代器内部的结构,仅需通过next()方法不断去取下一个内容
  2. 不能随机访问集合中的某个值 ,只能从头到尾依次访问
  3. 访问到一半时不能往回退
  4. 便于循环比较大的数据集合,节省内存

生成一个迭代器:

>>> a = iter([1,2,3,4,5])
>>> a
<list_iterator object at 0x101402630>
>>> a.__next__()
1
>>> a.__next__()
2
>>> a.__next__()
3
>>> a.__next__()
4
>>> a.__next__()
5
>>> a.__next__()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration

Repeated calls to the iterator’s __next__() method (or passing it to the built-in function next()) return successive items in the stream. When no more data are available a StopIteration exception is raised instead. At this point, the iterator object is exhausted and any further calls to its __next__() method just raise StopIteration again.

生成器generator

定义:一个函数调用时返回一个迭代器,那这个函数就叫做生成器(generator),如果函数中包含yield语法,那这个函数就会变成生成器

代码:

def cash_out(amount):
while amount >0:
amount -= 1
yield 1<br> print("擦,又来取钱了。。。败家子!")
ATM = cash_out(5)
print("取到钱 %s 万" % ATM.__next__())
print("花掉花掉!")
print("取到钱 %s 万" % ATM.__next__())
print("取到钱 %s 万" % ATM.__next__())
print("花掉花掉!")
print("取到钱 %s 万" % ATM.__next__())
print("取到钱 %s 万" % ATM.__next__())
print("取到钱 %s 万" % ATM.__next__()) #到这时钱就取没了,再取就报错了
print("取到钱 %s 万" % ATM.__next__())

作用:

这个yield的主要效果呢,就是可以使函数中断,并保存中断状态,中断后,代码可以继续往下执行,过一段时间还可以再重新调用这个函数,从上次yield的下一句开始执行。

另外,还可通过yield实现在单线程的情况下实现并发运算的效果

import time
def consumer(name):
print("%s 准备吃包子啦!" %name)
while True:
baozi = yield print("包子[%s]来了,被[%s]吃了!" %(baozi,name)) def producer(name):
c = consumer('A')
c2 = consumer('B')
c.__next__()
c2.__next__()
print("老子开始准备做包子啦!")
for i in range(10):
time.sleep(1)
print("做了2个包子!")
c.send(i)
c2.send(i) producer("alex")

Python高手之路【四】python函数装饰器,迭代器的更多相关文章

  1. 【Python 函数对象 命名空间与作用域 闭包函数 装饰器 迭代器 内置函数】

    一.函数对象 函数(Function)作为程序语言中不可或缺的一部分,但函数作为第一类对象(First-Class Object)却是 Python 函数的一大特性. 那到底什么是第一类对象(Firs ...

  2. Python--函数对象@命名空间与作用域@包函数@装饰器@迭代器@内置函数

    一.函数对象 函数(Function)作为程序语言中不可或缺的一部分,但函数作为第一类对象(First-Class Object)却是 Python 函数的一大特性. 那到底什么是第一类对象(Firs ...

  3. 【0812 | Day 13】闭包函数/装饰器/迭代器

    目录 闭包函数 无参装饰器 有参装饰器 迭代器 闭包函数 一.什么是闭包? 闭包指的是:函数内部函数对外部作用域而非全局作用域的引用. def outter(): x = 1 def inner(): ...

  4. python语言中的函数装饰器

    装饰器 什么是装饰器? 装饰:给已有的对象(函数)添加新的功能 器:工具              在python中指具备某些功能的函数 装饰器:装饰器就是一个给其他函数增加功能的函数 一种设计原则: ...

  5. Python高手之路【四】python函数装饰器

    def outer(func): def inner(): print('hello') print('hello') print('hello') r = func() print('end') p ...

  6. Python高手之路 ------读书有感

    最近忙中偷闲把前些年买的<Python高手之路>翻了出来,大致看完了一遍,其中很多内容并不理解,究其原因应该是实践中的经验不足,而这对于现如今的我仍是难以克服的事情,对此也就只能说是看会了 ...

  7. 简学Python第四章__装饰器、迭代器、列表生成式

    Python第四章__装饰器.迭代器 欢迎加入Linux_Python学习群  群号:478616847 目录: 列表生成式 生成器 迭代器 单层装饰器(无参) 多层装饰器(有参) 冒泡算法 代码开发 ...

  8. Python函数——装饰器

    前言 给下面的函数加上运行时间 def fib(n): a, b = 0, 1 for i in range(n): print(b) a, b = b, a+b return b a = fib(5 ...

  9. python闭包函数&装饰器

    一.函数引用 函数可以被引用 函数可以被赋值给一个变量 def hogwarts(): print("hogwarts") # hogwarts() # 函数调用 print(ho ...

随机推荐

  1. “Hello World!”团队第六周第六次会议

    “Hello World!”团队第六周第六次会议   博客内容: 一.会议时间 二.会议地点 三.会议成员 四.会议内容 五.todo list 六.会议照片 七.燃尽图 八.checkout& ...

  2. Java实验五(客户端)

    一.    实验内容 1.    运行教材上TCP代码,结对进行,一人服务器,一人客户端: 2.    利用加解密代码包,编译运行代码,客户端加密,服务器解密: 3.    客户端加密明文后将密文通过 ...

  3. Linux里的2>&1的理解

    转载自:https://blog.csdn.net/ggxiaobai/article/details/53507530 我们在Linux下经常会碰到nohup command>/dev/nul ...

  4. Eclipse+MySQL+Tomcat web开发安装配置

    转载文章: 链接:https://blog.csdn.net/bbyyz01/article/details/78142126 1.Eclipse 这里选择Eclipse集成开发环境. 可以直接在官网 ...

  5. week4d:个人博客作业

    7,程序结果的显示 1,界面 2,选第一选项. 3,输入3个数后. 4,选择第一个. 5,输入第4个数字. 6,再次进行一轮游戏. 7,选择是否要看历史记录. 8,进入下一轮游戏. 9,开始第二轮数字 ...

  6. Java 单生产者消费者问题

    package com.cwcec.test; class Resource { private int count = 0; private boolean flag = false; public ...

  7. windows下的C++ socket服务器(2)

    int main(int ac, char *av[]) { ); ) { exit(); } thread t; ) { int socket_fd = accept(tcp_socket, nul ...

  8. 解决在Mac上用pyenv安装python3失败的问题

    背景 前段时间在本地Mac系统上要跑一个python3写的压测脚本. Mac默认安装的是python2, 而且很多软件依赖的也是python2. 为了不影响现有系统其它软件, 当时安装了pyenv来实 ...

  9. HDU 2107 Founding of HDU

    http://acm.hdu.edu.cn/showproblem.php?pid=2107 Problem Description 经过慎重的考虑,XHD,8600, LL,Linle以及RPG等A ...

  10. [转帖]脑残式网络编程入门(二):我们在读写Socket时,究竟在读写什么?

    脑残式网络编程入门(二):我们在读写Socket时,究竟在读写什么?     http://www.52im.net/thread-1732-1-1.html   1.引言 本文接上篇<脑残式网 ...