python基础入门四

来源:互联网 发布:淘宝网新款针织衫 编辑:程序博客网 时间:2024/04/30 01:43

函数对象

一 函数是第一类对象,即函数可以当作数据传递
  1. 可以被引用
  2. 可以当作参数传递
  3. 返回值可以是函数
  4. 可以当作容器类型的元素
二 名称空间

名称空间:存放名字的地方,三种名称空间,(之前遗留的问题x=1,1存放于内存中,那名字x存放在哪里呢?名称空间正是存放名字x与1绑定关系的地方)
名称空间的加载顺序:
python test.py
1、python解释器先启动,因而首先加载的是:内置名称空间
2、执行test.py文件,然后以文件为基础,加载全局名称空间
3、在执行文件的过程中如果调用函数,则临时产生局部名称空间
名字的查找顺序
局部名称空间—>全局名称空间—>内置名称空间

三 装饰器

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

练习

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

import timedef timer():    def wrapper(func):        def inner(*args,**kwargs):            begin_time = time.time()            res = func(*args,**kwargs)            end_time = time.time()            used = end_time - begin_time            print("开始时间:",begin_time,"结束时间:",end_time,"用时:",used)            return res        return inner    return wrapperlogin_status = {'username':None,'status':False}def auth():    def wrapper(func):        def inner(*args,**kwargs):            if login_status['username'] and login_status['status']:                res = func(*args,**kwargs)                return res            else:                u = 'egon'                p = '123'                tag = True                while tag:                    name = input("输入用户名>>")                    passwd = input("输入密码>>")                    if name == u and passwd == p:                        print("登陆成功")                        res = func(*args, **kwargs)                        return res                    else:                        print("用户名或密码不正确,重新输入")                        continue        return inner    return wrapper@auth()@timer()def excute():    print("*****welcome***")    time.sleep(3)    print("nice job")excute()

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

import timeuser_status = {"name":None,"status":False}def auth(type='file'):    def wrapper(func):        def inner(*args,**kwargs):            if user_status['name'] and user_status['status']:                res = func(*args,**kwargs)                return res            else:                if type == 'file':                    with open('wenjian','r',encoding='utf-8') as read_f:                        dic = eval(read_f.read())                        us = input("输入用户名>>")                        pw = input("输入用户密码>>")                        if us in dic and pw == dic[us]:                            user_status['name'] = us                            user_status['status'] = True                            res = func(*args, **kwargs)                            return res                        else:                            print("用户名或者密码错误")                elif type == 'mysql':                    pass                else:                    pass        return inner    return wrapper@auth()def excute():    print("*****welcome***")    time.sleep(3)    print("nice job")@auth()def last():    print("已经登陆,无需登陆")    time.sleep(2)    print("good job")excute()last()

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

import timeuser_status = {"name":None,"status":False,"out_time":None}def auth(type='file'):    def wrapper(func):        def inner(*args,**kwargs):            if user_status['name'] and user_status['status']:                now = time.time()                if now - user_status['out_time'] < 3:                    res = func(*args,**kwargs)                    return res                else:                    print("登陆超时")            else:                if type == 'file':                    with open('wenjian','r',encoding='utf-8') as read_f:                        dic = eval(read_f.read())                        us = input("输入用户名>>")                        pw = input("输入用户密码>>")                        if us in dic and pw == dic[us]:                            user_status['name'] = us                            user_status['status'] = True                            user_status['out_time'] = time.time()                            res = func(*args, **kwargs)                            return res                        else:                            print("用户名或者密码错误")                elif type == 'mysql':                    pass                else:                    pass        return inner    return wrapper@auth()def excute():    print("*****welcome***")    time.sleep(3)    print("nice job")@auth()def last():    print("已经登陆,无需登陆")    time.sleep(2)    print("good job")excute()last()

六:编写下载网页内容的函数,要求功能是:用户传入一个url,函数返回下载页面的结果
七:为题目五编写装饰器,实现缓存网页内容的功能:
具体:实现下载的页面存放于文件中,如果文件内有值(文件大小不为0),就优先从文件中读取网页内容,否则,就去下载,然后存到文件中

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

import requests,os,hashlibengine_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'))

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

dic = {}def make(ch):    def wrap(func):        def inner():         dic[ch] = func        return inner    return wrap@make('select')def select():    print("select!!")@make('update')def update():    print("update!!")select()update()print(dic)

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

import timedef log(log):    def wrap(func):        def inner(*args,**kwargs):            res = func(*args,**kwargs)            aa = time.strftime('%Y-%m-%d %X')            with open(log,'a') as wrt:                info = aa +'--'+ func.__name__+'--' +'run' + '\n'                wrt.write(info)        return inner    return wrap@log(log='logs')def excute():    print("look up")@log(log='logs')def cat():    print("dog dog")excute()cat()

1、为何要有迭代器?
对于序列类型:字符串、列表、元组,我们可以使用索引的方式迭代取出其包含的元素。但对于字典、集合、文件等类型是没有索引的,若还想取出其内部包含的元素,则必须找出一种不依赖于索引的迭代方式,这就是迭代器

2、什么是可迭代对象?
可迭代对象指的是内置有iter方法的对象,即obj.iter,如下
‘hello’.iter
(1,2,3).iter
[1,2,3].iter
{‘a’:1}.iter
{‘a’,’b’}.iter
open(‘a.txt’).iter

3、什么是迭代器对象?
可迭代对象执行obj.iter()得到的结果就是迭代器对象
而迭代器对象指的是即内置有iter又内置有next方法的对象

文件类型是迭代器对象
open(‘a.txt’).iter()
open(‘a.txt’).next()

4、注意:
迭代器对象一定是可迭代对象,而可迭代对象不一定是迭代器对象

'''自定义模拟range'''def myrange(start,end,step):    while start < end:        yield start        start += stepfor k in myrange(1,9,2):    print(k)'''实现tail -f access.log |grep '404''''import timedef tail(file):    with open(file,'rb') as t:        t.seek(0,2)        while True:            data = t.read()            if data:                yield data            else:                time.sleep(2)def grep(pattern,lines):    for line in lines:        line = line.decode('utf-8')        if pattern in line:            yield linefor line in grep('404',tail('log')):    print(line,end='')