zoukankan      html  css  js  c++  java
  • 装饰器、生成器,迭代器、Json & pickle 数据序列化

    1、 列表生成器:代码例子

    1 a=[i*2 for i in range(10)]
    2 print(a)
    3 
    4 运行效果如下:
    5 D:python35python.exe D:/python培训/s14/day4/列表生成式.py
    6 [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
    7 
    8 Process finished with exit code 0

    2、高阶函数

    变量可以指向函数,函数的参数能接受变量,即把一个函数名当做实参传给另外一个函数 

    返回值中包涵函数名 

    代码例子:

     1 def test():
     2     print("int the test")
     3 
     4 def test2(func):
     5     print("in the test2")
     6     print(func)
     7     func()
     8 
     9 test2(test)
    10 运行效果如下:
    11 D:python35python.exe D:/python培训/s14/day4/高阶函数.py
    12 in the test2
    13 <function test at 0x000000000110E268>  #这里是test的内存地址
    14 int the test
    15 
    16 Process finished with exit code 0

    3、装饰器

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

    装饰器原则:

    a.不能修改被装饰的函数的源代码

    b.不能修改被装饰的函数的调用方式

    实现装饰器的知识储备:

    a、函数即“变量”

    b、高阶函数

    c、嵌套函数

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

    高阶函数:

    a.把一个函数名当做实参传给另外一个函数

    b.返回值中包含函数名

    代码例子

     1 import  time
     2 def timeer(func):
     3     def warpper():
     4         start_time=time.time()
     5         func()
     6         stop_time=time.time()
     7         print("the fun runn time is %s" %(stop_time-start_time))
     8     return warpper
     9 @timeer
    10 def test1():
    11     time.sleep(3)
    12     print("in the test1")
    13 
    14 test1()
    15 运行结果如下:
    16 D:python35python.exe D:/python培训/s14/day4/装饰器.py
    17 in the test1
    18 the fun runn time is 3.000171661376953
    19 
    20 Process finished with exit code 0

    带参数的装饰器

     1 import time
     2 
     3 def timer(func):
     4     def deco(*args,**kwargs):
     5         start_time=time.time()
     6         func(*args,**kwargs)
     7         stop_time=time.time()
     8         print("the func runn time is %s" %(stop_time-start_time))
     9     return deco
    10 
    11 @timer  #test1 = timer(test1)
    12 def test1():
    13     time.sleep(3)
    14     print("in the test1")
    15 
    16 @timer
    17 
    18 def test2(name,age):
    19     print("name:%s,age:%s" %(name,age))
    20 
    21 test1()
    22 test2("zhaofan",23)
    23 运行结果如下:
    24 
    25 D:python35python.exe D:/python培训/s14/day4/装饰器3.py
    26 in the test1
    27 the func runn time is 3.000171661376953
    28 name:zhaofan,age:23
    29 the func runn time is 0.0
    30 
    31 Process finished with exit code 0

    终极版的装饰器

     1 import time
     2 user,passwd = "zhaofan","123"
     3 def auth(auth_type):
     4     print("auth func:",auth_type)
     5     def outer_wrapper(func):
     6         def wrapper(*args,**kwargs):
     7             if auth_type=="local":
     8                 username = input("Username:").strip()
     9                 password = input("Password:").strip()
    10                 if user == username and passwd== password:
    11                     print("33[32;1mUser has passed authentication33[0m")
    12                     res = func(*args,**kwargs)
    13                     print("------after authentication")
    14                     return res
    15                 else:
    16                     exit("33[31;1mInvalid username or password33[0m")
    17             elif auth_type=="ldap":
    18                 print("没有ldap")
    19         return wrapper
    20     return outer_wrapper
    21 
    22 def index():
    23     print("welcome to index page")
    24 @auth(auth_type="local")
    25 def home():
    26     print("welcome to home page")
    27     return "from home"
    28 @auth(auth_type="ldap")
    29 def bbs():
    30     print("welcome to bbs page")
    31 
    32 index()
    33 print(home())
    34 bbs()
    35 
    36 
    37 运行结果如下:
    38 D:python35python.exe D:/python培训/s14/day4/装饰器4.py
    39 auth func: local
    40 auth func: ldap
    41 welcome to index page
    42 Username:zhaofan
    43 Password:123
    44 User has passed authentication
    45 welcome to home page
    46 ------after authentication
    47 from home
    48 没有ldap
    49 
    50 Process finished with exit code 0

    4、通过列表生成式,我们可以直接创建一个列表。但是,受到内存限制,列表容量肯定是有限的。而且,创建一个包含100万个元素的列表,不仅占用很大的存储空间,如果我们仅仅需要访问前面几个元素,那后面绝大多数元素占用的空间都白白浪费了。

    所以,如果列表元素可以按照某种算法推算出来,那我们是否可以在循环的过程中不断推算出后续的元素呢?这样就不必创建完整的list,从而节省大量的空间。在Python中,这种一边循环一边计算的机制,称为生成器:generator。

     1 a = [x for x in range(10)]
     2 print(a)
     3 
     4 g=(x for x in range(10))
     5 print(g)
     6 运行结果如下:
     7 D:python35python.exe D:/python培训/s14/day4/生成器.py
     8 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
     9 <generator object <genexpr> at 0x0000000000B01DB0>
    10 
    11 Process finished with exit code 0

    生成器只有一个方法:__next__()

    generator保存的是算法,每次调用next(g),就计算出g的下一个元素的值,直到计算到最后一个元素,没有更多的元素时,抛出StopIteration的错误。

     1 g=(x for x in range(10))
     2 
     3 for i in g:
     4     print(i)
     5 
     6 
     7 运行结果如下:
     8 
     9 D:python35python.exe D:/python培训/s14/day4/生成器的调用.py
    10 0
    11 1
    12 2
    13 3
    14 4
    15 5
    16 6
    17 7
    18 8
    19 9
    20 
    21 Process finished with exit code 0

    5、可以直接作用于for循环的数据类型有以下几种

    一类是集合数据类型,如listtupledictsetstr等;

    一类是generator,包括生成器和带yield的generator function。

    这些可以直接作用于for循环的对象统称为可迭代对象:Iterable

    可以使用isinstance()判断一个对象是否是Iterable对象

    可以被next()函数调用并不断返回下一个值的对象称为迭代器:Iterator

    生成器都是Iterator对象,但listdictstr虽然是Iterable,却不是Iterator

    凡是可作用于for循环的对象都是Iterable类型;

    凡是可作用于next()函数的对象都是Iterator类型,它们表示一个惰性计算的序列;

    集合数据类型如listdictstr等是Iterable但不是Iterator,不过可以通过iter()函数获得一个Iterator对象。

    6、json和pickle

  • 相关阅读:
    在 Eclipse Workbench 之外使用 Eclipse GUI
    GB2312,GBK,Unicode
    木偶一之推荐系统
    Matlab:任意矩阵计算分布密度(海明距离的分布密度)
    live555在arm linux下的交叉编译,并下载的Arm板播放H264文件
    java设计模式之原型模式
    HDU 1102
    poj3661另一种做法(滚动数组)
    基于QT的小游戏细菌病毒战
    某代码查看器的保护突破
  • 原文地址:https://www.cnblogs.com/zhaof/p/5786807.html
Copyright © 2011-2022 走看看