• python--函数


    函数          原文请参考。。。。。。。。。








    一:为何用函数之不使用函数的问题
    #组织结构不清晰
    #代码冗余
    #无法统一管理且维护难度大


    二:函数分类:
    1. 内置函数
    2. 自定义函数


    三:为何要定义函数
    函数即变量,变量必须先定义后使用,未定义而直接引用函数,就相当于在引用一个不存在的变量名
    代码演示?

    四:定义函数都干了哪些事?
    只检测语法,不执行代码


    五:如何定义函数(函数名要能反映其意义)
    def ...


    六:定义函数的三种形式
    无参:应用场景仅仅只是执行一些操作,比如与用户交互,打印
    有参:需要根据外部传进来的参数,才能执行相应的逻辑,比如统计长度,求最大值最小值
    空函数:设计代码结构


    七 :函数的调用
    1 先找到名字
    2 根据名字调用代码
      
      函数的返回值?
      0->None
      1->返回1个值
      多个->元组

      什么时候该有?
        调用函数,经过一系列的操作,最后要拿到一个明确的结果,则必须要有返回值
        通常有参函数需要有返回值,输入参数,经过计算,得到一个最终的结果
      什么时候不需要有?
        调用函数,仅仅只是执行一系列的操作,最后不需要得到什么结果,则无需有返回值
        通常无参函数不需要有返回值

    八:函数调用的三种形式
    1 语句形式:foo()
    2 表达式形式:3*len('hello')
    4 当中另外一个函数的参数:range(len('hello'))

    九:函数的参数:
    1 形参和实参定义
    2 形参即变量名,实参即变量值,函数调用则将值绑定到名字上,函数调用结束,解除绑定
    3 具体应用
    位置参数:按照从左到右的顺序定义的参数
    位置形参:必选参数
    位置实参:按照位置给形参传值

    关键字参数:按照key=value的形式定义实参
    无需按照位置为形参传值
    注意的问题:
    1. 关键字实参必须在位置实参右面
    2. 对同一个形参不能重复传值

    默认参数:形参在定义时就已经为其赋值
    可以传值也可以不传值,经常需要变得参数定义成位置形参,变化较小的参数定义成默认参数(形参)
    注意的问题:
    1. 只在定义时赋值一次
    2. 默认参数的定义应该在位置形参右面
    3. 默认参数通常应该定义成不可变类型


    可变长参数:
    针对实参在定义时长度不固定的情况,应该从形参的角度找到可以接收可变长实参的方案,这就是可变长参数(形参)
    而实参有按位置和按关键字两种形式定义,针对这两种形式的可变长,形参也应该有两种解决方案,分别是*args,**kwargs

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

    def foo(x,y,*args):
    print(x,y)
    print(args)
    foo(1,2,*[3,4,5])


    def foo(x,y,z):
    print(x,y,z)
    foo(*[1,2,3])

    ===========**kwargs===========
    def foo(x,y,**kwargs):
    print(x,y)
    print(kwargs)
    foo(1,y=2,a=1,b=2,c=3)

    def foo(x,y,**kwargs):
    print(x,y)
    print(kwargs)
    foo(1,y=2,**{'a':1,'b':2,'c':3})


    def foo(x,y,z):
    print(x,y,z)
    foo(**{'z':1,'x':2,'y':3})

    ===========*args+**kwargs===========

    def foo(x,y):
    print(x,y)

    def wrapper(*args,**kwargs):
    print('====>')
    foo(*args,**kwargs)

    命名关键字参数:*后定义的参数,必须被传值(有默认值的除外),且必须按照关键字实参的形式传递
    可以保证,传入的参数中一定包含某些关键字
    def foo(x,y,*args,a=1,b,**kwargs):
    print(x,y)
    print(args)
    print(a)
    print(b)
    print(kwargs)

    foo(1,2,3,4,5,b=3,c=4,d=5)
    结果:
    1
    2
    (3, 4, 5)
    1
    3
    {'c': 4, 'd': 5}

    六道练习题 
    1、写函数,,用户传入修改的文件名,与要修改的内容,执行函数,完成批了修改操作
    def a(filename,old,new):
        import os
        with open(filename,'r') as read_f,open('filenam','w') as write_f:
            for line in read_f:
                if old in line:
                    line=line.replace(old,new)
                    write_f.write(line)
        os.remove(filename)
        os.rename('filenam',filename)
    print(a('a.txt',' ','  '))

    # 2、写函数,计算传入字符串中【数字】、【字母】、【空格] 以及 【其他】的个数
    def func1(args):
        dic = {"num":0,"str":0,"space":0,"other":0}
        while True:
            for i in args:
                if i.isdigit():
                    dic["num"] += 1
                elif i.isalpha():
                    dic["str"] += 1
                elif i.isspace():
                    dic["space"] += 1
                else:
                    dic["other"] += 1
            return dic
    print(func1("vdnvkdlknd ekfn1234r kglvklvkn _+-+"))

    # 3、写函数,判断用户传入的对象(字符串、列表、元组)长度是否大于5。

    def func(args):
        if isinstance(args, str) or isinstance(args, list) or isinstance(args, tuple):
            if len(args) > 5:
                print("> 5")
            else:
                print("< 5")
        else:
            print("请重新输入字符串,列表,元祖三种类型")
            #continue
    al=int(12324566)
    print(type(al))
    func(al)
    # 4、写函数,检查传入列表的长度,如果大于2,那么仅保留前两个长度的内容,并将新内容返回给调用者。

    def func1(file):
        dic={}
        if len(file) >2:
            file = file[:2]
            return file
        else:
            return file
    print(func1("fee"))
    打开一个网站的链接
    from urllib.request import urlopen
    def index(url):
        def get():
            return urlopen(url).read()
        return get
    baidu=index('http://www.baidu.com')
    print(baidu())

    # 5、写函数,检查获取传入列表或元组对象的所有奇数位索引对应的元素,并将其作为新列表返回给调用者
    # def func1(l):
    #     li=[]
    #     if isinstance(l, list) or isinstance(l, tuple):
    #         for i in l[::2]:
    #             li.append(i)
    #         print(li)
    def se(seq):
        return seq[::2]
    print(se(('1','2','3','4','5','6')))

    #func1(('1','2','3','4','5','6'))

    # 6、写函数,检查字典的每一个value的长度,如果大于2,那么仅保留前两个长度的内容,并将新内容返回给调用者。
    def func1(kwargs):
        for keys,values in kwargs.items():
            if len(kwargs[keys]) > 2:
                kwargs[keys]=kwargs[keys][0:2]
        return kwargs
    print(func1({"fe":"rrr","rrr":[1,2,3,4]}))

    #def func3(dic):
    #    d={}
    #    for k,v in dic.items():
    #        if len(v) > 2:
    #            d[k]=v[0:2]
    #    return d
    #print(func3({'k1':'abcdef','k2':[1,2,3,4],'k3':('a','b','c')}))



        一:函数对象:函数是第一类对象,即函数可以当作数据传递
    1 可以被引用
    2 可以当作参数传递
    3 返回值可以是函数
    3 可以当作容器类型的元素
    #利用该特性,优雅的取代多分支的if
    def foo():
    print('foo')

    def bar():
    print('bar')

    dic={
    'foo':foo,
    'bar':bar,
    }
    while True:
    choice=input('>>: ').strip()
    if choice in dic:
    dic[choice]()

    二:函数的嵌套
    1 函数的嵌套调用
    def max(x,y):
    return x if x > y else y

    def max4(a,b,c,d):
    res1=max(a,b)
    res2=max(res1,c)
    res3=max(res2,d)
    return res3
    print(max4(1,2,3,4))

    2 函数的嵌套定义
    def f1():
    def f2():
    def f3():
    print('from f3')
    f3()
    f2()

    f1()
    f3() #报错


    三 名称空间和作用域:
    名称空间:存放名字的地方,三种名称空间,(之前遗留的问题x=1,1存放于内存中,那名字x存放在哪里呢?名称空间正是存放名字x与1绑定关系的地方)
    加载顺序是?
    名字的查找顺序?(在全局无法查看局部的,在局部可以查看全局的)
            # max=1
    def f1():
    # max=2
    def f2():
    # max=3
    print(max)
    f2()
    f1()
    print(max)


    作用域即范围
         - 全局范围:全局存活,全局有效
         - 局部范围:临时存活,局部有效
    - 作用域关系是在函数定义阶段就已经固定的,与函数的调用位置无关,如下
          x=1
          def f1():
          def f2():
          print(x)
          return f2

          def f3(func):
          x=2
          func()

          f3(f1())


    查看作用域:globals(),locals()

    global
    nonlocal


    LEGB 代表名字查找顺序: locals -> enclosing function -> globals -> __builtins__
    locals 是函数内的名字空间,包括局部变量和形参
    enclosing 外部嵌套函数的名字空间(闭包中常见)
    globals 全局变量,函数定义所在模块的名字空间
    builtins 内置模块的名字空间



    四:闭包:内部函数包含对外部作用域而非全局作用域的引用
    提示:之前我们都是通过参数将外部的值传给函数,闭包提供了另外一种思路,包起来喽,包起呦,包起来哇

    def counter():
    n=0
    def incr():
    nonlocal n
    x=n
    n+=1
    return x
    return incr

    c=counter()
    print(c())
    print(c())
    print(c())
    print(c.__closure__[0].cell_contents) #查看闭包的元素



    闭包的意义:返回的函数对象,不仅仅是一个函数对象,在该函数外还包裹了一层作用域,这使得,该函数无论在何处调用,优先使用自己外层包裹的作用域
    应用领域:延迟计算(原来我们是传参,现在我们是包起来)
    from urllib.request import urlopen

    def index(url):
    def get():
    return urlopen(url).read()
    return get

    baidu=index('http://www.baidu.com')
    print(baidu().decode('utf-8'))


    五: 装饰器(闭包函数的一种应用场景)

    1 为何要用装饰器:
    开放封闭原则:对修改封闭,对扩展开放

    2 什么是装饰器
    装饰器他人的器具,本身可以是任意可调用对象,被装饰者也可以是任意可调用对象。
    强调装饰器的原则:1 不修改被装饰对象的源代码 2 不修改被装饰对象的调用方式
    装饰器的目标:在遵循1和2的前提下,为被装饰对象添加上新功能

    3. 先看简单示范
    import time
    def timmer(func):
    def wrapper(*args,**kwargs):
    start_time=time.time()
    res=func(*args,**kwargs)
    stop_time=time.time()
    print('run time is %s' %(stop_time-start_time))
    return res
    return wrapper

    @timmer
    def foo():
    time.sleep(3)
    print('from foo')
    foo()


    4
    def auth(driver='file'):
    def auth2(func):
    def wrapper(*args,**kwargs):
    name=input("user: ")
    pwd=input("pwd: ")

    if driver == 'file':
    if name == 'egon' and pwd == '123':
    print('login successful')
    res=func(*args,**kwargs)
    return res
    elif driver == 'ldap':
    print('ldap')
    return wrapper
    return auth2

    @auth(driver='file')
    def foo(name):
    print(name)

    foo('egon')

    5 装饰器语法:
    被装饰函数的正上方,单独一行
    @deco1
    @deco2
    @deco3
    def foo():
    pass

    foo=deco1(deco2(deco3(foo)))

      6 装饰器补充:wraps
    from functools import wraps
    
    def deco(func):
        @wraps(func) #加在最内层函数正上方
        def wrapper(*args,**kwargs):
            return func(*args,**kwargs)
        return wrapper
    
    @deco
    def index():
        '''哈哈哈哈'''
        print('from index')
    
    print(index.__doc__)
      7 装饰器练习

    一:编写函数,(函数执行的时间是随机的)
    二:编写装饰器,为函数加上统计时间的功能
    三:编写装饰器,为函数加上认证的功能

    四:编写装饰器,为多个函数加上认证的功能(用户的账号密码来源于文件),要求登录成功一次,后续的函数都无需再输入用户名和密码
    注意:从文件中读出字符串形式的字典,可以用eval('{"name":"egon","password":"123"}')转成字典格式

    五:编写装饰器,为多个函数加上认证功能,要求登录成功一次,在超时时间内无需重复登录,超过了超时时间,则必须重新登录

    六:编写下载网页内容的函数,要求功能是:用户传入一个url,函数返回下载页面的结果

    七:为题目五编写装饰器,实现缓存网页内容的功能:
    具体:实现下载的页面存放于文件中,如果文件内有值(文件大小不为0),就优先从文件中读取网页内容,否则,就去下载,然后存到文件中

    扩展功能:用户可以选择缓存介质/缓存引擎,针对不同的url,缓存到不同的文件中

    八:还记得我们用函数对象的概念,制作一个函数字典的操作吗,来来来,我们有更高大上的做法,在文件开头声明一个空字典,然后在每个函数前加上装饰器,完成自动添加到字典的操作

    九 编写日志装饰器,实现功能如:一旦函数f1执行,则将消息2017-07-21 11:12:11 f1 run写入到日志文件中,日志文件路径可以指定
    注意:时间格式的获取
    import time
    time.strftime('%Y-%m-%d %X')

    #题目一:略
    #题目二:略
    #题目三:略
    #题目四:
    db='db.txt'
    login_status={'user':None,'status':False}
    def auth(auth_type='file'):
        def auth2(func):
            def wrapper(*args,**kwargs):
                if login_status['user'] and login_status['status']:
                    return func(*args,**kwargs)
                if auth_type == 'file':
                    with open(db,encoding='utf-8') as f:
                        dic=eval(f.read())
                    name=input('username: ').strip()
                    password=input('password: ').strip()
                    if name in dic and password == dic[name]:
                        login_status['user']=name
                        login_status['status']=True
                        res=func(*args,**kwargs)
                        return res
                    else:
                        print('username or password error')
                elif auth_type == 'sql':
                    pass
                else:
                    pass
            return wrapper
        return auth2
    
    @auth()
    def index():
        print('index')
    
    @auth(auth_type='file')
    def home(name):
        print('welcome %s to home' %name)
    
    
    # index()
    # home('egon')
    
    #题目五
    import time,random
    user={'user':None,'login_time':None,'timeout':0.000003,}
    
    def timmer(func):
        def wrapper(*args,**kwargs):
            s1=time.time()
            res=func(*args,**kwargs)
            s2=time.time()
            print('%s' %(s2-s1))
            return res
        return wrapper
    
    
    def auth(func):
        def wrapper(*args,**kwargs):
            if user['user']:
                timeout=time.time()-user['login_time']
                if timeout < user['timeout']:
                    return func(*args,**kwargs)
            name=input('name>>: ').strip()
            password=input('password>>: ').strip()
            if name == 'egon' and password == '123':
                user['user']=name
                user['login_time']=time.time()
                res=func(*args,**kwargs)
                return res
        return wrapper
    
    @auth
    def index():
        time.sleep(random.randrange(3))
        print('welcome to index')
    
    @auth
    def home(name):
        time.sleep(random.randrange(3))
        print('welcome %s to home ' %name)
    
    index()
    home('egon')
    
    #题目六:略
    #题目七:简单版本
    import requests
    import os
    cache_file='cache.txt'
    def make_cache(func):
        def wrapper(*args,**kwargs):
            if not os.path.exists(cache_file):
                with open(cache_file,'w'):pass
    
            if os.path.getsize(cache_file):
                with open(cache_file,'r',encoding='utf-8') as f:
                    res=f.read()
            else:
                res=func(*args,**kwargs)
                with open(cache_file,'w',encoding='utf-8') as f:
                    f.write(res)
            return res
        return wrapper
    
    @make_cache
    def get(url):
        return requests.get(url).text
    
    
    # res=get('https://www.python.org')
    
    # print(res)
    
    #题目七:扩展版本
    import requests,os,hashlib
    engine_settings={
        'file':{'dirname':'./db'},
        'mysql':{
            'host':'127.0.0.1',
            'port':3306,
            'user':'root',
            'password':'123'},
        'redis':{
            'host':'127.0.0.1',
            'port':6379,
            'user':'root',
            'password':'123'},
    }
    
    def make_cache(engine='file'):
        if engine not in engine_settings:
            raise TypeError('egine not valid')
        def deco(func):
            def wrapper(url):
                if engine == 'file':
                    m=hashlib.md5(url.encode('utf-8'))
                    cache_filename=m.hexdigest()
                    cache_filepath=r'%s/%s' %(engine_settings['file']['dirname'],cache_filename)
    
                    if os.path.exists(cache_filepath) and os.path.getsize(cache_filepath):
                        return open(cache_filepath,encoding='utf-8').read()
    
                    res=func(url)
                    with open(cache_filepath,'w',encoding='utf-8') as f:
                        f.write(res)
                    return res
                elif engine == 'mysql':
                    pass
                elif engine == 'redis':
                    pass
                else:
                    pass
    
            return wrapper
        return deco
    
    @make_cache(engine='file')
    def get(url):
        return requests.get(url).text
    
    # print(get('https://www.python.org'))
    print(get('https://www.baidu.com'))
    
    
    #题目八
    route_dic={}
    
    def make_route(name):
        def deco(func):
            route_dic[name]=func
        return deco
    @make_route('select')
    def func1():
        print('select')
    
    @make_route('insert')
    def func2():
        print('insert')
    
    @make_route('update')
    def func3():
        print('update')
    
    @make_route('delete')
    def func4():
        print('delete')
    
    print(route_dic)
    
    
    #题目九
    import time
    import os
    
    def logger(logfile):
        def deco(func):
            if not os.path.exists(logfile):
                with open(logfile,'w'):pass
    
            def wrapper(*args,**kwargs):
                res=func(*args,**kwargs)
                with open(logfile,'a',encoding='utf-8') as f:
                    f.write('%s %s run
    ' %(time.strftime('%Y-%m-%d %X'),func.__name__))
                return res
            return wrapper
        return deco
    
    @logger(logfile='aaaaaaaaaaaaaaaaaaaaa.log')
    def index():
        print('index')
    
    index()
    
    
    def make_cache(engine='file'):
        if engine not in engine_settings:
            raise TypeError('egine not valid')
        def deco(func):
            def wrapper(url):
                if engine == 'file':
                    m=hashlib.md5(url.encode('utf-8'))
                    cache_filename=m.hexdigest()
                    cache_filepath=r'%s/%s' %(engine_settings['file']['dirname'],cache_filename)
    
                    if os.path.exists(cache_filepath) and os.path.getsize(cache_filepath):
                        return open(cache_filepath,encoding='utf-8').read()
    
                    res=func(url)
                    with open(cache_filepath,'w',encoding='utf-8') as f:
                        f.write(res)
                    return res
                elif engine == 'mysql':
                    pass
                elif engine == 'redis':
                    pass
                else:
                    pass
    
            return wrapper
        return deco
    
    @make_cache(engine='file')
    def get(url):
        return requests.get(url).text
    
    # print(get('https://www.python.org'))
    print(get('https://www.baidu.com'))
    
    
    #题目八
    route_dic={}
    
    def make_route(name):
        def deco(func):
            route_dic[name]=func
        return deco
    @make_route('select')
    def func1():
        print('select')
    
    @make_route('insert')
    def func2():
        print('insert')
    
    @make_route('update')
    def func3():
        print('update')
    
    @make_route('delete')
    def func4():
        print('delete')
    
    print(route_dic)
    
    
    #题目九
    import time
    import os
    
    def logger(logfile):
        def deco(func):
            if not os.path.exists(logfile):
                with open(logfile,'w'):pass
    
            def wrapper(*args,**kwargs):
                res=func(*args,**kwargs)
                with open(logfile,'a',encoding='utf-8') as f:
                    f.write('%s %s run
    ' %(time.strftime('%Y-%m-%d %X'),func.__name__))
                return res
            return wrapper
        return deco
    
    @logger(logfile='aaaaaaaaaaaaaaaaaaaaa.log')
    def index():
        print('index')
    index()
    ') index()
     
  • 相关阅读:
    chrome webkitappearance
    图片占用内存
    javascript性能优化repaint和reflow
    vim 系统剪切板
    CSS选择符的命名(转载)
    relative 内部 margin
    中国软件企业
    dom元素排序
    shell
    tips for asm
  • 原文地址:https://www.cnblogs.com/DE_LIU/p/7258260.html
Copyright © 2020-2023  润新知