• 函数与装饰器Python学习(三)


    1.1 文件处理

    1.1.1 打开文件过程

    在Python中,打开文件,得到文件句柄并赋值给一个变量,默认打开模式就为r

    f=open(r'a.txt','w',encoding='utf-8')
    
    print(f.writable())
    通过句柄对文件进行操作
    f.write('1111
    ')
    
    f.write('2222
    ')
    
    f.writelines(['3333
    ','444
    '])
    关闭文件
    f.close()

    1.1.2 打开文件过程分析

    1、由应用程序向操作系统发起系统调用open(...)
    2、操作系统打开该文件,并返回一个文件句柄给应用程序
    3、应用程序将文件句柄赋值给变量f

    1.1.3 注意要点:

    第一点:
    打开一个文件包含两部分资源:操作系统级打开的文件+应用程序的变量。在操作完毕一个文件时,必须把与该文件的这两部分资源一个不落地回收,回收方法为:
    1、f.close() #回收操作系统级打开的文件
    2、del f #回收应用程序级的变量
    其中del f一定要发生在f.close()之后,否则就会导致操作系统打开的文件还没有关闭,白白占用资源,而python自动的垃圾回收机制决定了我们无需考虑del f,这就要求我们,在操作完毕文件后,一定要记住f.close()
    为避免忘记忘记f.close(),使用with关键字来帮我们管理
    with open('a.txt','w') as f:
    
        pass
    
     
    
    with open('a.txt','r') as read_f,open('b.txt','w') as write_f:
    
        data=read_f.read()
    
        write_f.write(data)
    强调第二点:
    f=open(...)是由操作系统打开文件,那么如果我们没有为open指定编码,那么打开文件的默认编码很明显是操作系统说了算了,操作系统会用自己的默认编码去打开文件,在windows下是gbk,在linux下是utf-8。
    这就用到了上节课讲的字符编码的知识:若要保证不乱码,文件以什么方式存的,就要以什么方式打开。
    f=open('a.txt','r',encoding='utf-8')

    1.1.4 三种模式:a,r,b

    打开文件的模式有(默认为文本模式)

    1.1.5 a:之追加写模式(不可读;不存在则创建;存在则只追加内容)

    文件不存在则创建,文件存在那么在打开文件后立刻将光标移动到文件末尾,进行追加写

    f=open(r'b.txt','a',encoding='utf-8')
    
    print(f.writable())
    
    f.write('4444
    ')  
    
    f.write('5555
    ')
    
    f.writelines(['66666
    ','7777
    ']) 
    
    f.close()
    
     

    1.1.6 r:只读模式(默认模式,文件必须存在,不存在则抛出异常)

    f=open(r'b.txt','r',encoding='utf-8')
    
    print(f.writable())
    
    print(f.read())
    
    print(f.readlines())
    
    print(f.readline(),end='')
    
    print(f.readline(),end='')
    
    f.close() 
     
    with open('b.txt','r',encoding='utf-8') as f:
    
        while True:
    
            line=f.readline()
    
            if len(line) == 0:break
    
            print(line)
    
     
    
        print(f.readline())
    
        print(f.readline())
    
        print(f.readline())
    
        print(f.readline())
    
        print(f.readline())
    
        print(f.readline())
    
        print(f.readline())
    
        print('第八次',f.readline())
    
    #
    
        for line in f:
    
            print(line)
     

    1.1.7 w,只写模式(不可读;不存在则创建;存在则清空内容)

    1.1.8 b:bytes表示以字节的方式操作(而所有文件也都是以字节的形式存储的,使用这种模式无需考虑文本文件的字符编码、图片文件的jgp格式、视频文件的avi格式)

    with open('111.png','rb') as f:
        print(f.read())

     

    with open('b.txt','rb',) as f:
    
        print(f.read().decode('utf-8'))

     

    with open('b.txt','rt',encoding='utf-8') as f:
    
        print(f.read())
    with open('b.txt','wb') as f:
    
        res='中问'.encode('utf-8')
    
        print(res,type(res))
    
        f.write(res)
    with open('b.txt','ab') as f:
    
        res='哈哈哈'.encode('utf-8')
    
        print(res,type(res))
    
        f.write(res)

     

    注:以b方式打开时,读取到的内容是字节类型,写入时也需要提供字节类型,不能指定编码

    1.2 字符编码补充

    #encoding:utf-8
    
    with open('b.txt','rt',encoding='utf-8') as f:
    
        print(f.read())
    
     

    1.3 操作文件的方法

    1.3.1 文件修改

    文件的数据是存放于硬盘上的,因而只存在覆盖、不存在修改这么一说,我们平时看到的修改文件,都是模拟出来的效果,具体的说有两种实现方式:

    1.3.1.1  利用b模式,编写一个cp工具,要求如下:

    1. 既可以拷贝文本又可以拷贝视频,图片等文件

    2. 用户一旦参数错误,打印命令的正确使用方法

    提示:可以用import sys,然后用sys.argv获取脚本后面跟的参数

    方式一:将硬盘存放的该文件的内容全部加载到内存,在内存中是可以修改的,修改完毕后,再由内存覆盖到硬盘(word,vim,nodpad++等编辑器)

    import os
    
    with open('info.txt','r',encoding='utf-8') as read_f,open('.info.txt.swap','w',encoding='utf-8') as write_f:
    
        data=read_f.read()
    
        write_f.write(data.replace('alex','SB'))
    
     
    
    os.remove('info.txt')
    
    os.rename('.info.txt.swap','info.txt')

     

    方式二:将硬盘存放的该文件的内容一行一行地读入内存,修改完毕就写入新文件,最后用新文件覆盖源文件

    import os
    
     
    
    with open('info.txt', 'r', encoding='utf-8') as read_f, open('.info.txt.swap', 'w', encoding='utf-8') as write_f:
    
        for line in read_f:
    
            if 'SB' in line:
    
                line=line.replace('SB','alex')
    
            write_f.write(line)
    
     
    
    os.remove('info.txt')
    
    os.rename('.info.txt.swap', 'info.txt')

    cp复制命令的实现

    1、源大小的问题:

    2、文件打开模式的问题:b

    #!/usr/bin/env python
    
    import sys
    
    _,src_file,dst_file=sys.argv
    
     
    
    with open(src_file,'rb') as read_f,
    
            open(dst_file,'wb') as write_f:
    
        # data=read_f.read()
    
        # write_f.write(data)
    
     
    
        for line in read_f:
    
            write_f.write(line)
    
            write_f.flush()

     

    1.3.2 文件内光标的移动

    f.read() #读取所有内容,光标移动到文件末尾

    f.readline() #读取一行内容,光标移动到第二行首部

    f.readlines() #读取每一行内容,存放于列表中

    f.write('1111 222 ') #针对文本模式的写,需要自己写换行符

    f.write('1111 222 '.encode('utf-8')) #针对b模式的写,需要自己写换行符

    f.writelines(['333 ','444 ']) #文件模式

    f.writelines([bytes('333 ',encoding='utf-8'),'444 '.encode('utf-8')]) #b模式

    1.3.2.1  : read(3):

    1. 文件打开方式为文本模式时,代表读取3个字符

    2. 文件打开方式为b模式时,代表读取3个字节

    1.3.2.2  : 其余的文件内光标移动都是以字节为单位如seek,tell,truncate

    注意:

    1. seek有三种移动方式0,1,2,其中1和2必须在b模式下进行,但无论哪种模式,都是以bytes为单位移动的

    2. truncate是截断文件,所以文件的打开方式必须可写,但是不能用w或w+等方式打开,因为那样直接清空文件了,所以truncate要在r+或a或a+等模式下测试效果

    1.3.2.3      基于seek实现tail -f功能

    with open('a.txt','r',encoding='utf-8') as f:
    
        data1=f.read()
    
        print('==1==>',data1)
    
        print(f.tell())
    
     
    
        data2=f.read()
    
        print('==2==>',data2)
    只有一种情况光标以字符为单位:文件以rt方式打开,read(3)
    with open('c.txt','rt',encoding='utf-8') as f:
    
        print(f.read(6))
    
        print(f.tell())
    
        f.seek(0,0)
    
        print(f.read(6))
    
     
    
        f.seek(6,0)
    
        f.seek(8,0)
    
        print(f.read())
     
    with open('c.txt','rb',) as f:
    
        f.seek(6,0)
    
        # f.seek(8,0)
    
        print(f.read())
    with open('c.txt','rb') as f:
    
        print(f.read(6))
    
        f.seek(2,1)
    
        print(f.tell())
    
        print(f.read().decode('utf-8'))

    1.4 函数基础

    1.4.1 为什么要有函数?没有函数带来的困扰?

    Ø  组织结构不清晰,可读性差
    Ø  代码冗余
    Ø  可扩展性差
     

    1.4.2 什么是函数

       具备某一个功能的工具---》函数
        事先准备工具-》函数的定义
        拿来就用、重复使用-》函数的调用
        ps:先定义后调用
     

    1.4.3 函数的分类:

        内置函数:len,max(10,11),help(函数名)
        自定义函数:def
            语法:

                def 函数名(参数1,参数2,...):

                    """注释"""

                    函数体

                    return 返回值

    '''

    #'函数即是变量'
    def print_tag():
    
        print('*'*20)
    
     
    
    def print_msg(): #print_msg=<function print_msg at 0x00000000027EA8C8>
    
        print('hello world')
    
     
    
     
    
    print(print_msg)
    
    print(print_tag)
    
     
    
    print_tag()
    
    print_msg()
    
    print_tag()
     

    1.4.4 定义函数阶段都发生了什么事:只检测语法,不执行代码

    1.4.4.1  定义阶段

    sex='male'
    
    def auth():
    
        sex
    
     
    
        name=input('name>>: ').strip()
    
        password=input('password>>: ').strip()
    
        if name =='egon' and password == '123':
    
            print('login successfull')
    
        else:
    
            print('user or password err')
     

    1.4.4.2  调用阶段

    auth()
    
     

    1.4.5 函数的使用:先定义后调用

    def bar():
    
        print('from bar')
    
     
    
    def foo():
    
        print('from foo')
    
        bar()
    
     
    
    foo()
     
    定义阶段
    def foo():
    
        print('from foo')
    
        bar()
    定义阶段
    def bar():
    
        print('from bar')
    调用
    def bar():
    
        print('from bar')
     
     

    1.4.6 定义函数的三种形式

    1、无参:应用场景仅仅只是执行一些操作,比如与用户交互,打印

    2、有参:需要根据外部传进来的参数,才能执行相应的逻辑,比如统计长度,求最大值最小值

    3、空函数:设计代码结构

    1.4.6.1  第一种:无参函数

     
    def auth():
    
        name=input('name>>: ').strip()
    
        password=input('password>>: ').strip()
    
        if name =='egon' and password == '123':
    
            print('login successfull')
    
        else:
    
            print('user or password err')

    1.4.6.2  第二种:有参函数

    def my_max(x,y):
    
        if x >= y:
    
            print(x)
    
        else:
    
            print(y)
    
     
    
    my_max(1,2)

     

    1.4.6.3  第三种:空函数

    def auth(name,password):
    
        if name =='egon' and password == '123':
    
            print('login successfull')
    
        else:
    
            print('user or password err')
    
     
    
    def interactive():
    
        name=input('name>>: ').strip()
    
        password=input('password>>: ').strip()
    
        auth(name,password)
    
     
    
    interactive()

    1.4.7 结论:

    1、定义时无参,意味着调用时也无需传入参数
    2、定义时有参,意味着调用时则必须传入参数

    1.4.8 程序的体系结构

    def auth():
    
        pass
    
     
    
    def put():
    
        pass
    
     
    
    def get():
    
        pass
    
     
    
    def ls():
    
        pass

    1.5 函数的返回值

    无return->None

    return 1个值->返回1个值

    return 逗号分隔多个值->元组

    1.5.1 return的特点:

    1、 函数内可以有多个return,但是只能执行一次return

    2、 执行return函数就立刻结束,并且return的后值当做本次调用的结果返回

    1.5.1.1  什么时候该有返回值?

      调用函数,经过一系列的操作,最后要拿到一个明确的结果,则必须要有返回值

      通常有参函数需要有返回值,输入参数,经过计算,得到一个最终的结果

    1.5.1.2  什么时候不需要有返回值?

      调用函数,仅仅只是执行一系列的操作,最后不需要得到什么结果,则无需有返回值

      通常无参函数不需要有返回值

    1.5.2 函数调用的三种形式

    1.5.2.1  语句形式:foo()

    def foo(x,y):
    
        return x+y
    
     
    
    res=foo(1,2)
    
     
    
    def my_max(x,y):
    
        if x >= y:
    
            return x
    
        else:
    
            return y
    
     
    
    res=my_max(1,2)
    
    print(res)
    def foo():
    
        print('first')
    
        return 1
    
        print('second')
    
        return 2
    
        print('third')
    
        return 3
    
     
    
    res=foo()
    
    print(res)

    1.6 函数的参数

    1.6.1 函数的参数分类两种:

    形参:在定义阶段括号内指定的参数,相当于变量名
    实参:在调用阶段括号内传入的值称之为实参,相当于值

    1.6.2 在调用阶段,实参的值会绑定给形参,在调用结束后解除绑定

    def foo(x,y): #x=1,y=2
    
        print(x,y)
    
     
    
    foo(1,2)
    

    1.6.3 在python中参数的分类:

    1.6.3.1  位置参数:按照从左到右的顺序依次定义的参数

    位置形参:必须被传值,多一个少一个都不行
    位置实参:与形参一一对应传值
    def foo(x,y):
    
        print(x,y)
    
     
    
    foo(2,1)
    

    1.6.3.2  关键字参数:在函数调用时,按照key=value的形式定义的实参

    特点:指名道姓地给形参传值,不再依赖与位置
    def foo(name,age,sex):
    
        print(name,age,sex)
    
     
    
    foo('egon',18,'male')
    
    foo(sex='male',age=18,name='egon',)
    注意:
    1、 关键字实参必须在位置实参的后面
    2、 不能为同一个参数赋值多次
    foo('egon',sex='male',age=18,name='egon'

    1.6.3.3  默认参数:在函数定义阶段,就已经为形参赋值了

    特点:定义阶段已经有值意味着调用阶段可以不用传值
    位置参数通常用于经常变化的参数,而默认参数指的是大多数情况下都一样的
    def foo(x,y=1):
    
        print(x,y)
    
     
    
    foo(1,2)
    
    foo(y=3,x=1)
    
    foo(111)
    
    foo(x=1111)
    def register(name,age,sex='male'):
    
        print(name,age,sex)
    
     
    
    register('egon1',18)
    
    register('egon2',18)
    
    register('egon3',18)
    
    register('alex',38,'female')
    注意:
    1、默认参数必须放到位置形参的后面
    def register(name,sex='male',age,):
        print(name,age,sex)
    2、默认参数的值只在定义时被赋值一次
    3、默认的参数的值通常应该是不可变类型
    res=1
    
    def foo(x,y=res):
    
        print(x,y)
    
     
    
    res=10
    
    foo('aaaaaaaa')

    1.6.3.4  可变长参数:在调用函数时,实参值的个数不固定

    实参的形式有:位置实参和关键字实参,
    形参的解决方案:*,**
    Ø  *args的用法
    def foo(x,y,*args): #z=(3,4,5,6)
    
        print(x,y)
    
        print(args)
    
     
    
    foo(1,2,3,4,5,6)
    
     
    
    foo(1,2,*[3,4,5,6]) #foo(1,2,3,4,5,6)
    
    foo(*[1,2,3,4,5,6]) #foo(1,2,3,4,5,6)
    
     
    def foo(x,y):
    
        print(x,y)
    
     
    
    foo(*(1,2)) #foo(1,2)
     
    Ø  **kwargs
    def foo(x,y,**kwargs): #kwargs={'c':5,'a':3,'b':4}
    
        print(x,y)
    
        print(kwargs)
    
     
    
    foo(y=2,x=1,a=3,b=4,c=5)
    
     
    
    foo(y=2,**{'c':5,'x':1,'b':4,'a':3}) #foo(y=2,a=3,c=5,b=4)
    
     
    
    def foo(name,age):
    
        print(name,age)
    
     
    
    foo(**{'name':'egon','age':18})
    
    foo({'name':'egon','age':18})
    
     
    
    def bar(x,y,z):
    
        print(x,y,z)

     

    def wrapper(*args,**kwargs): #args=(1,),kwargs={'z':2,'y':3}
    
        # print(args,kwargs)
    
        bar(*args,**kwargs) #bar(*(1,),**{'z':2,'y':3}) #bar(1,z=2,y=3,)
    
     
    
    wrapper(1,z=2,y=3)
     

    1.6.3.5  命名关键字参数:指的是定义在*后的参数,该参数必须被传值(除非有它有默认值),而且必须按照key=value的形式传值

    def foo(x,y,*args,m=100000,n):
    
        print(x,y)
    
        print(args)
    
        print(m,n)
    
     
    
    foo(1,2,3,n=4,)

    1.7 函数的对象

    1.7.1 函数是第一类对象:指的是函数可以当做数据传递

    1.7.1.1  可以被引用 x=1,y=x

    def func(x,y):
    
        print(x,y)
    
     
    
    f=func
    
    f(1,2)

    1.7.1.2  可当做函数的参数传入

    def foo():
    
        print('from foo')
    
     
    
    def bar(func):
    
        # print(func)
    
        func()
    
     
    
    bar(foo)

    1.7.1.3  可以当做函数的返回值

    def foo():
    
        print('from foo')
    
     
    
    def bar():
    
        return foo
    
     
    
    f=bar()
    
    f()

    1.7.1.4  可以当做容器类型的元素

    def foo():
    
        print('from foo')
    
     
    
    def bar():
    
        return foo
    
     
    
    l=[foo,bar]
    
    print(l)
    
    l[0]()
    def get():
    
        print('get')
    
     
    
    def put():
    
        print('put')
    
     
    
    def ls():
    
        print('ls')
    
     
    
    cmd=input('>>: ').strip()
    
    if cmd == 'get':
    
        get()
    
    elif cmd == 'put':
    
        put()
    
    elif cmd == 'ls':
    
        ls()
    
     
    
     
    
    def get():
    
        print('get')
    
     
    
    def put():
    
        print('put')
    
     
    
    def ls():
    
        print('ls')
    
     
    
    def auth():
    
        print('auth')
    
     
    
    func_dic={
    
        'get':get,
    
        'put':put,
    
        'ls':ls,
    
        'auth':auth
    
    }
    
    # func_dic['put']()
    
    cmd = input('>>: ').strip()
    
    if cmd in func_dic:
    
        func_dic[cmd]()

     

    1.8 函数的嵌套

    1.8.1 函数的嵌套调用

    def my_max(x,y):
    
        if x >= y:
    
            return x
    
        else:
    
            return y
     
    def my_max4(a,b,c,d):
    
        res1=my_max(a,b)
    
        res2=my_max(res1,c)
    
        res3=my_max(res2,d)
    
        return res3
     

    1.8.2 函数的嵌套定义

    def f1():
    
        def f2():
    
            print('from f2')
    
            def f3():
    
                print('from f3')
    
            f3()
    
        # print(f2)
    
        f2()
    
     
    
     
    
    f1()
    
     

    1.9 名称空间

    名称空间指的是:存放名字与值绑定关系的地方,

    1.9.1 内置与全局名称空间

    内置名称空间(python解释器启动就有):python解释器内置的名字,max,len,print

    全局名称空间(执行python文件时生效):文件级别定义的名字

    x=1
    
    def func():pass
    
    import time
    
    if x == 1:
    
        y=2
     
    
    #局部名称空间(函数调用时生效,调用结束失效):函数内部定义的名字
    
    func()

    1.9.2 加载与访问顺序

    加载顺序:内置---》全局----》局部名称空间

    访问名字的顺序:局部名称空间===》全局----》内置

    x=1
    
    print(x)

     

    #print(max)
    
     
    
    max=2
    
    def func():
    
        # max=1
    
        print(max)
    func()
    
     
    
    x='gobal'
    
    def f1():
    
        # x=1
    
        def f2():
    
           # x=2
    
           def f3():
    
               # x=3
    
               print(x)
    
           f3()
    
        f2()
    
     
    
    f1()

    1.9.3 全局与局部作用域

    全局作用域(全局范围):内置名称空间与全局名称空间的名字,全局存活,全局有效,globals()

    局部作用域(局部范围):局部名称空间的名字,临时存活,局部有效,locals()

    #xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx=111111111111111111111
    
    print(globals())
    
    print(dir(globals()['__builtins__']))
    
     
    
    print(locals() is globals())
    
     
    
    def func():
    
      #  yyyyyyyyyyyyyyyyyyyyyyyy=22222222
    
        print(globals())
    
        print(locals())
    
     
    
    func()
    
     
    
    x=100
    
    def func():
    
        global x
    
        x=1
    
     
    
    func()
    
    print(x)
    
     
    
    x='global'
    
    def f1():
    
        # x=1
    
        def f2():
    
            nonlocal x
    
            x=0
    
        f2()
    
        print('===f1 innter--->',x)
    
     
    
    f1()
    
    print(x)

    1.9.4 强调两点:

    1.9.4.1  打破函数层级限制来调用函数

    def outter():
    
        def inner():
    
            print('inner')
    
        return inner
    
     
    
    f=outter()
    
    # print(f)
    
     
    
    def bar():
    
        f()
    
    bar()

    1.9.4.2  函数的作用域关系是在函数定义阶段就已经固定了,与调用位置无关

    x=1
    
    def outter():
    
        # x=2
    
        def inner():
    
            print('inner',x)
    
        return inner
    
     
    
    f=outter()
    
    # print(f)
    
    # x=1111111111111111111111111111111111111111111111111111111111111111111111111111111111
    
    def bar():
    
        x=3
    
        f()
    
    # x=1111111111111111111111111111111111111111111111111111111111111111111111111111111111
    
    bar()
    
    x=1111111111111111111111111111111111111111111111111111111111111111111111111111111111 

    1.10 闭包函数

    闭包函数:

    1 定义在函数内部的函数

    2 该函数的函数体代码包含对外部作用域(而不是全局作用域)名字的引用

    3 通常将闭包函数用return返回,然后可以在任意使用

    z=1
    
    def outer():
    
        x=1
    
        y=2
    
        def inner():
    
            print(x,y)
    
            # print(z)
    
        return inner
    
     
    
    f=outer()
    
    print(f.__closure__[0].cell_contents)
    
    print(f.__closure__[1].cell_contents)
    
    print(f.__closure__)
    def bar():
    
        x=111121
    
        y=2222
    
        f()
    
     
    
    bar()
    def foo(x,y):
    
        print(x+y)
    
     
    
    foo(1,2)
    
     

     

    def outter():
    
        x=1
    
        y=2
    
        def foo():
    
            print(x+y)
    
        return foo
    
     
    
     
    
    f=outter()
    
     
    
    f()

    1.10.1 闭包的意义:

    返回的函数对象,不仅仅是一个函数对象,在该函数外还包裹了一层作用域,这使得,该函数无论在何处调用,优先使用自己外层包裹的作用域

    1.10.2 应用领域:

    延迟计算(原来我们是传参,现在我们是包起来)

    1.10.3 爬页面:闭包函数为我们提供了一种新的为函数传参的方式

    import requests #pip3 install requests
    
     
    
    def get(url):
    
        response=requests.get(url)
    
        if response.status_code == 200:
    
            print(len(response.text))
    
     
    
    get('https://www.baidu.com')
    
    get('https://www.baidu.com')
    
    get('https://www.baidu.com')
    
     
    
    def outter(url):
    
        # url = 'https://www.baidu.com'
    
        def get():
    
            response=requests.get(url)
    
            if response.status_code == 200:
    
                print(len(response.text))
    
        return get
    
     
    
    baidu=outter('https://www.baidu.com')
    
    python=outter('https://www.python.org')
    
    # baidu()
    
    # baidu()
    
    # baidu()

    1.11 装饰器

    1.11.1 开放封闭原则:

    对扩展开放,对修改是封闭

    1.11.2 装饰器:

    装饰它人的,器指的是任意可调用对象,现在的场景装饰器-》函数,被装饰的对象也是-》函数

    1.11.3 原则:

    1、不修改被装饰对象的源代码

    2、不修改被装饰对象的调用方式

    1.11.4 装饰器的目的:

    在遵循1,2的前提下为被装饰对象添加上新功能

    错误的示范

    import time
    
     
    
    def index():
    
        time.sleep(3)
    
        print('welecome to index')
    
     
    
    def timmer(func):
    
        start=time.time()
    
        func()
    
        stop=time.time()
    
        print('run time is %s' %(stop-start))
    
     
    
    timmer(index)

    1.11.5 正确的示范

    import time
    
    def index():
    
        time.sleep(3)
    
        print('welecome to index')
    
     
    
    def timmer(func):
    
        # func=index #最原始的index
    
        def inner():
    
            start=time.time()
    
            func() #最原始的index
    
            stop=time.time()
    
            print('run time is %s' %(stop-start))
    
        return inner
    
     
    
    index=timmer(index) #index=inner
    
    # print(f)
    
    index() #inner()

    1.12 装饰器的修订

    1.12.1 装饰器语法:

    在被装饰对象正上方单独一行写上,@装饰器名

    @deco1
    
            @deco2
    
            @deco3
    
            def foo():
    
                pass
    
     
    
            foo=deco1(deco2(deco3(foo)))

    1.12.2 改进一:

    import time
    
    def timmer(func):
    
        def inner():
    
            start=time.time()
    
            res=func()
    
            stop=time.time()
    
            print('run time is %s' %(stop-start))
    
            return res
    
        return inner
    
     
    
    @timmer #index=timmer(index)
    
    def index():
    
        time.sleep(1)
    
        print('welecome to index')
    
        return 1111
    
     
    
    res=index() #res=inner()
    
    print(res)

    1.12.3 改进二:

    import time
    
    def timmer(func):
    
        def inner(*args,**kwargs):
    
            start=time.time()
    
            res=func(*args,**kwargs)
    
            stop=time.time()
    
            print('run time is %s' %(stop-start))
    
            return res
    
        return inner
    
     
    
    @timmer #index=timmer(index)
    
    def index(name):
    
        time.sleep(1)
    
        print('welecome %s to index' %name)
    
        return 1111
    
    res=index('egon') #res=inner('egon')
    
    print(res)
    
     
    
    @timmer #home=timmer(home)
    
    def home(name):
    
        print('welcome %s to home page' %name)
    
     
    
    home('egon') #inner('egon')
    
     

    1.13 有参装饰器

    import time
    
    def auth(func): # func=index
    
        def inner(*args,**kwargs):
    
            name=input('name>>: ').strip()
    
            password=input('password>>: ').strip()
    
            if name == 'egon' and password == '123':
    
                print('login successful')
    
                return func(*args,**kwargs)
    
            else:
    
                print('login err')
    
        return inner
    
     
    
    @auth
    
    def index(name):
    
        time.sleep(1)
    
        print('welecome %s to index' %name)
    
        return 1111
    
     
    
    res=index('egon')
    
    print(res)

    #有参装饰器

    import time
    
     
    
    def auth2(engine='file'):
    
        def auth(func): # func=index
    
            def inner(*args,**kwargs):
    
                if engine == 'file':
    
                    name=input('name>>: ').strip()
    
                    password=input('password>>: ').strip()
    
                    if name == 'egon' and password == '123':
    
                        print('login successful')
    
                        return func(*args,**kwargs)
    
                    else:
    
                        print('login err')
    
                elif engine == 'mysql':
    
                    print('mysql auth')
    
                elif engine == 'ldap':
    
                    print('ldap auth')
    
                else:
    
                    print('engin not exists')
    
            return inner
    
        return auth
    
     
    
    @auth2(engine='mysql') #@auth #index=auth(index) #index=inner
    
    def index(name):
    
        time.sleep(1)
    
        print('welecome %s to index' %name)
    
        return 1111
    
     
    
    res=index('egon') #res=inner('egon')
    
    print(res)

    1.14 并列多个装饰器

    import time
    
    def timmer(func):
    
        def inner(*args,**kwargs):
    
            start=time.time()
    
            res=func(*args,**kwargs)
    
            stop=time.time()
    
            print('run time is %s' %(stop-start))
    
            return res
    
        return inner
    
     
    
    def auth2(engine='file'):
    
        def auth(func): # func=index
    
            def inner(*args,**kwargs):
    
                if engine == 'file':
    
                    name=input('name>>: ').strip()
    
                    password=input('password>>: ').strip()
    
                    if name == 'egon' and password == '123':
    
                        print('login successful')
    
                        return func(*args,**kwargs)
    
                    else:
    
                        print('login err')
    
                elif engine == 'mysql':
    
                    print('mysql auth')
    
                elif engine == 'ldap':
    
                    print('ldap auth')
    
                else:
    
                    print('engin not exists')
    
            return inner
    
        return auth
    
     
    
     
    
    @auth2(engine='file')
    
    @timmer
    
    def index(name):
    
        time.sleep(1)
    
        print('welecome %s to index' %name)
    
        return 1111
    
     
    
    res=index('egon')
    
    print(res)

    1.15 wraps补充

    from functools import wraps
    
    import time
    
    def timmer(func):
    
        @wraps(func)
    
        def inner(*args,**kwargs):
    
            start=time.time()
    
            res=func(*args,**kwargs)
    
            stop=time.time()
    
            print('run time is %s' %(stop-start))
    
            return res
    
        # inner.__doc__=func.__doc__
    
        # inner.__name__=func.__name__
    
        return inner
    
     
    
    @timmer
    
    def index(name): #index=inner
    
        '''index 函数。。。。。'''
    
        time.sleep(1)
    
        print('welecome %s to index' %name)
    
        return 1111
    
     
    
    # res=index('egon')
    
    # print(res)
    
     
    
    print(help(index))
  • 相关阅读:
    四套读写方案
    如何保证ArrayList线程安全
    异常总结<经典例题>
    java.移位运算符
    java反射机制
    面试题:return和finally执行
    Spring_通过注解配置 Bean(1)
    Spring_通过 FactoryBean 配置 Bean
    Spring_通过工厂方法配置 Bean
    Spring_管理 Bean 的生命周期
  • 原文地址:https://www.cnblogs.com/x-y-j/p/8076512.html
Copyright © 2020-2023  润新知