一、装饰器

定义:本质是函数,(装饰其他函数)就是为其它函数添加附加功能

原则:1、不能修改被装饰的函数的源代码

2、不能修改被装饰的函数的调用方式

实现装饰器知识储备:

1、函数及“变量”

2、高阶函数

a、把一个函数名当做实参传给另一个函数(在不修改被装饰器函数源代码的情况下为其添加新功能)

b、返回值中包含函数名

3、嵌套函数

高阶函数+嵌套函数 = 装饰器

延迟3秒

import time

def test1():
time.sleep(3)
print('in the test1')
test1()#延迟3秒

例一:装饰器

def bar ():
print("in the bar")
def foo ():
print ("in the foo")
bar()
foo()

例二:

def deco(func):
start_time = time.time()
func()
return func
stop_time = time.time()
print ("in func run time is %s" %(stop_time-start_time))
return deco
def foo ():
print("in the foo")
bar()
def bar():
print("in the bar")
foo()

例三:

import time
def timer(func):
def deco (*args, **kwargs):
start_time = time.time()
func(*args, **kwargs)
stop_time = time.time()
print("in func run time is %s" %(stop_time- start_time))
return deco
@timer #等于test1 = timer(test1)
def test1():
time.sleep(3)
print('in the test1')
test1()
@timer
def test2(name,age):
time.sleep(3)
print("in the :",name age)
test2('liudong',23)

例四:终极装饰器

user,passwd = 'liudong',''
def auth (auth_type):
print("auth_func:",auth_type)
def outer_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")
res = func(*args, **kwargs)#form home
print("------------after authentication ")
return res
else:
exit("\033[31;1mInvalid username or password\033[0m")
elif auth_type == "ldap":
print("不会-------------")
return wrapper
return outer_wrapper
def index():
print("welcome to index page")
@auth(auth_type="local") #home = wrapper
def home ():
print("welcome to home page")
return "form home"
@auth(auth_type="ldap")
def bbs():
print("welcome to bbs page")
index()
print(home()) #wrapper()
bbs()

匿名函数:

res = filter(lambda n:n>5,range(10))
for i in res:
print(i)

#print(globals())  打印整个文件里的所有你变量

二、迭代器&生成器

1、只有在调试时,才会生成相应的数据

2、c.__nest__ 一个一个的往下生成,只记录当前的位置,之前生成过的就没了。

3、只有一个__nest__()方法

生成器

def fib (max):
n, a, b = 0, 0, 1
while n < max:
yield b
a, b = b, a + b
n = n + 1
return '------------done-------------'
g = fib(10)
while True:
try:
x = next(g)
print('g:', x)
except StopAsyncIteration as e:
print('Generator return value:', e.value)
break

生成器并行

def consumer(name):
print("%s准备吃包子了" %name)
while True:
baozi = yield
print("包子[%s]来了,被[%s]吃了" %(baozi,name))
c = consumer("liudong")
c.__next__()
c.send('胡萝卜馅,人肉馅') def producer(name):
c = consumer('A')
c2 = consumer('B')
c.__next__()
c2.__next__()
print("老子开始吃包子啦!")
for i in range(5):
time.sleep(1)
print("做了1个包子,分两半!")
c.send(i)
c2.send(i)
producer("liudong")

#迭代器 可以使用isinstance()判断一个对象是否是Iterator(迭代器)对象

json序列化

info = {'name':'liudong','age':23}
f = open("test.txt","w")
f.write(json.dumps(info))
f.close()

day4装饰器-迭代器&&生成器的更多相关文章

  1. Day4 装饰器——迭代器——生成器

    一 装饰器 1.1 函数对象 一 函数是第一类对象,即函数可以当作数据传递 #1 可以被引用 #2 可以当作参数传递 #3 返回值可以是函数 #3 可以当作容器类型的元素 二 利用该特性,优雅的取代多 ...

  2. python中的装饰器迭代器生成器

    装饰器: 定义:本质是函数(装饰其它函数) 为其它函数添加附加功能 原则: 1 不能修改被装饰函数源代码    2 不修改被装饰函数调用方式 实现装饰器知识储备: 1 函数即‘’变量‘’ 2 高阶函数 ...

  3. Python学习---装饰器/迭代器/生成器的学习【all】

    Python学习---装饰器的学习1210 Python学习---生成器的学习1210 Python学习---迭代器学习1210

  4. day04 装饰器 迭代器&生成器 Json & pickle 数据序列化 内置函数

    回顾下上次的内容 转码过程: 先decode  为 Unicode(万国码 ) 然后encode 成需要的格式     3.0 默认是Unicode  不是UTF-8 所以不需要指定  如果非要转为U ...

  5. python_装饰器——迭代器——生成器

    一.装饰器 1.什么是装饰器? 器=>工具,装饰=>增加功能 1.不修改源代码 2.不修改调用方式 装饰器是在遵循1和2原则的基础上为被装饰对象增加功能的工具 2.实现无参装饰器 1.无参 ...

  6. python装饰器,迭代器,生成器,协程

    python装饰器[1] 首先先明白以下两点 #嵌套函数 def out1(): def inner1(): print(1234) inner1()#当没有加入inner时out()不会打印输出12 ...

  7. python笔记3 闭包 装饰器 迭代器 生成器 内置函数 初识递归 列表推导式 字典推导式

    闭包 1, 闭包是嵌套在函数中的 2, 闭包是内层函数对外层函数的变量(非全局变量)的引用(改变) 3,闭包需要将其作为一个对象返回,而且必须逐层返回,直至最外层函数的返回值 闭包例子: def a1 ...

  8. Python中的装饰器,迭代器,生成器

    1. 装饰器 装饰器他人的器具,本身可以是任意可调用对象,被装饰者也可以是任意可调用对象. 强调装饰器的原则:1 不修改被装饰对象的源代码 2 不修改被装饰对象的调用方式 装饰器的目标:在遵循1和2的 ...

  9. 装饰器、生成器,迭代器、Json & pickle 数据序列化

    1. 列表生成器:代码例子 a=[i*2 for i in range(10)] print(a) 运行效果如下: D:\python35\python.exe D:/python培训/s14/day ...

随机推荐

  1. 简化LINUX的命令输入 简化linux命令 快捷键 短路径

    在LINUX中,有很多常用的命令,常用的命令我们可以熟练的记忆,但是对于不经常使用的命令恐怕是需要翻阅手册了,但是我们可以简化这些命令的输入来达到简便记忆的效果. 这里以BSH为例: 编辑/etc/b ...

  2. 【Android开发—智能家居系列】(四):UDP通信发送指令

    思路回顾 [1]手机连接WIFI模块 [2]UDP通信对WIFI模块发送指令,以和WIFI模块保持连接状态 [3]UDP通信对WIFI模块发送指令,让其搜索可用的无线网,返回WIFI列表 [4]发送指 ...

  3. 王立平--Gallery:实现图片的左右滑动

    <span style="font-size:18px;color:#330033;">package com.main; import android.app.Act ...

  4. sklearn preprocessing data(数据预处理)

    参考: http://scikit-learn.org/stable/modules/preprocessing.html

  5. fatal error C1189: #error : core.hpp header must be compiled as C++

    两次opencv工程需要设置为C++编译:找了一半天的解决方法. I am building a C application that uses OpenCV. when compiling, I g ...

  6. Hbase调用JavaAPI实现批量导入操作

    将手机上网日志文件批量导入到Hbase中.操作步骤: 1.将日志文件(请下载附件)上传到HDFS中,利用hadoop的操作命令上传:hadoop  fs -put input  / 2.创建Hbase ...

  7. SolidEdge 如何绘制零件图的剖视图

    1 点击检视-剖面,然后选择剖切面   2 比如要全剖,则绘制好方框之后点返回,选择方向.   选择剖切深度,然后预览即可   一个零件可以进行多次剖切

  8. 关于结构体的具体解说,C、C++中的差别

    1. C.C++内置的类型分两种,一种是基本数据类型.一种是复合数据类型.此处我们要讲的结构体便是复合数据类型. 先来讨论一下结构体存在的意义吧.或许你觉得主要的数据类型就够了,为什么还要有结构题这样 ...

  9. Go fsm

    package fsm import ( "log" ) type EvtIf interface { GetEvtType() string } type Action inte ...

  10. C#复习总结4

    第十三章 委托 什么是委托 委托就是函数的指针. 其和类相似,其实就是用户自定义的引用类型. 委托是包含有序方法列表的对象,这些方法具有相同的签名和返回类型. MyDel delvar = new M ...