zoukankan      html  css  js  c++  java
  • LearnPython_week4

    1、装饰器
    2、生成器
    3、迭代器
    4、内置方法
    5、可序列化
    6、项目规范化

    1、装饰器

    # -*- coding:utf-8 -*-
    # Author:Wong Du
    
    ### 原代码
    def home():
        print("Welcome to home...")
    def shoe():
        print("Welcome to shoe...")
    def clothes():
        print("Welcome to clothes...")
    def gift():
        print("Welcome to gift...")
    home()
    shoe()
    clothes()
    gift()
    
    #################需求:为程序的购物专区增加认证功能#################
    ### Part1:添加认证函数login(),加入到需要认证模块的函数当中
    user = 'Wong'
    passwd = 'Wong123'
    def login():
        count = 0
        while count < 3:
            username = input('User login: ')
            password = input('Password: ')
            if username == user and password == passwd:
                print("Login successful...")
                break
            else:
                print("Invalid username or password...")
            count += 1
    
    def home():
        print("Welcome to home...")
    def shoe():
        login()
        print("Welcome to shoe...")
    def clothes():
        login()
        print("Welcome to clothes...")
    def gift():
        login()
        print("Welcome to gift...")
    home()
    shoe()
    clothes()
    gift()
    
    #################需求:为程序的购物专区增加认证功能#################
    ### Part2:添加认证函数login(func),在login()中调用需要添加认证功能的函数
    user = 'Wong'
    passwd = 'Wong123'
    def login(func):
        count = 0
        while count < 3:
            username = input('User login: ')
            password = input('Password: ')
            if username == user and password == passwd:
                print("Login successful...")
                func()
                break
            else:
                print("Invalid username or password...")
            count += 1
    
    def home():
        print("Welcome to home...")
    def shoe():
        print("Welcome to shoe...")
    def clothes():
        print("Welcome to clothes...")
    def gift():
        print("Welcome to gift...")
    home()
    # shoe()
    # clothes()
    # gift()
    login(shoe)
    login(clothes)
    login(gift)
    
    #################需求:为程序的购物专区增加认证功能#################
    ### Part3:添加认证函数login(func),函数赋值,再调用
    user = 'Wong'
    passwd = 'Wong123'
    def login(func):
        count = 0
        while count < 3:
            username = input('User login: ')
            password = input('Password: ')
            if username == user and password == passwd:
                print("Login successful...")
                func()
                break
            else:
                print("Invalid username or password...")
            count += 1
        return login    #高阶函数,返回login的内存地址
    
    def home():
        print("Welcome to home...")
    def shoe():
        print("Welcome to shoe...")
    def clothes():
        print("Welcome to clothes...")
    def gift():
        print("Welcome to gift...")
    home()
    # shoe()
    # clothes()
    # gift()
    # shoe = login(shoe)
    # clothes = login(clothes)
    # gift = login(gift)
    # shoe()
    # clothes()
    # gift()
    
    #################需求:为程序的购物专区增加认证功能#################
    ### Part4:添加认证函数login(func),嵌套函数+高阶函数,函数赋值,再调用
    user = 'Wong'
    passwd = 'Wong123'
    def login(func):
        def auth():
            count = 0
            while count < 3:
                username = input('User login: ')
                password = input('Password: ')
                if username == user and password == passwd:
                    print("Login successful...")
                    func()
                    break
                else:
                    print("Invalid username or password...")
                count += 1
        return auth    #高阶函数,返回login的内存地址
    
    def home():
        print("Welcome to home...")
    def shoe():
        print("Welcome to shoe...")
    def clothes(name):
        print("%s,Welcome to clothes..." %name)
    def gift():
        print("Welcome to gift...")
    home()
    shoe = login(shoe)
    clothes = login(clothes)
    gift = login(gift)
    shoe()
    clothes()
    gift()
    
    ### Part5:添加不固定参数,增加装饰器的可扩展性
    user = 'Wong'
    passwd = 'Wong123'
    def login(func,*args,**kwargs):
        def auth(*args,**kwargs):
            count = 0
            while count < 3:
                username = input('User login: ')
                password = input('Password: ')
                if username == user and password == passwd:
                    print("Login successful...")
                    func(*args,**kwargs)
                    break
                else:
                    print("Invalid username or password...")
                count += 1
        return auth    #高阶函数,返回login的内存地址
    
    def home():
        print("Welcome to home...")
    def shoe():
        print("Welcome to shoe...")
    def clothes(name,*args,**kwargs):
        print("%s,Welcome to clothes..." %name)
    def gift():
        print("Welcome to gift...")
    home()
    # shoe = login(shoe)
    clothes = login(clothes)
    # gift = login(gift)
    # shoe()
    clothes('Wong')
    # gift()
    
    ### Part6:函数赋值的方式看起来太low了,用装饰器专用调用方法
    user = 'Wong'
    passwd = 'Wong123'
    def login(func,*args,**kwargs):
        def auth(*args,**kwargs):
            count = 0
            while count < 3:
                username = input('User login: ')
                password = input('Password: ')
                if username == user and password == passwd:
                    print("Login successful...")
                    func(*args,**kwargs)
                    break
                else:
                    print("Invalid username or password...")
                count += 1
        return auth    #高阶函数,返回login的内存地址
    
    def home():
        print("Welcome to home...")
    @login      #相当于shoe = login(shoe)
    def shoe():
        print("Welcome to shoe...")
    @login      #相当于shoe = login(clothes)
    def clothes(name,*args,**kwargs):
        print("%s,Welcome to clothes..." %name)
    @login      #相当于shoe = login(gift)
    def gift():
        print("Welcome to gift...")
    home()
    # shoe()
    clothes('Wong')
    # gift()
    
    ### Part7:为函数添加不同平台qq/wechat/weibo等认证功能
    user = 'Wong'
    passwd = 'Wong123'
    def login(auth_type,*args,**kwargs):
        def auth(func,*args,**kwargs):
            def inner(*args,**kwargs):
                if auth_type == 'qq':
                    count = 0
                    while count < 3:
                        username = input('User login: ')
                        password = input('Password: ')
                        if username == user and password == passwd:
                            print("Login successful...")
                            func(*args,**kwargs)
                            break
                        else:
                            print("Invalid username or password...")
                        count += 1
                else:
                    print("Sorry,Only support qq login...")
            return inner    #高阶函数,返回login的内存地址
        return auth
    
    def home():
        print("Welcome to home...")
    @login('qq')      #相当于shoe = login(shoe)
    def shoe():
        print("Welcome to shoe...")
    @login('weibo')      #相当于shoe = login(clothes)
    def clothes(name,*args,**kwargs):
        print("%s,Welcome to clothes..." %name)
    @login('wechat')      #相当于shoe = login(gift)
    def gift():
        print("Welcome to gift...")
    home()
    shoe()
    clothes('Wong')
    gift()
    View Code

    2、生成器

    # -*- coding:utf-8 -*-
    # Author:Wong Du
    
    
    '''
    生成器 generator
    生成器最直观的效果就是节省内存
        1.传统的列表等集合体是把所有元素存在内存里,当我们需要某个元素时,再从集合体里调用,此方式耗费内存,效率低下
        2.生成器可以理解为是把一套计算方法和一个内存地址绑定在一起,这个内存地址里面没有生成元素,当我们需要某个元素时,再通过内存地址里面的算法一个一个生成元素
    制造生成器:
        1.g = (x*2 for x in range(10))
        2.用yield在函数中定义,把整个函数制造成一个生成器
    特性:
        生成器只能向后生成元素
        生成器有两种调用方式
            1. __next__方法
                g.__next__()
            2. for循环调用
                for i in g:
                    print(i)
    '''
    
    ### 制造生成器和类型说明
    g = (x*2 for x in range(10))
    print(type(g))
    print(g)
    '''
    输出:
    <class 'generator'>
    <generator object <genexpr> at 0x0000000000A2A938>
    '''
    
    ### 生成器的调用特点
    print(g.__next__())
    print(next(g))
    print("走走神。。。")
    print(next(g))
    print(g.__next__())
    print("发发呆。。。")
    for i in g:
        print(i)
    
    ### 函数生成器,
    ## 生成器的send方法可以给yield赋值
    print('华丽分割线'.center(40,'*'))
    # def fib(max):       #普通函数
    #     n,a,b = 0,0,1
    #     while max > n:
    #         print(b)
    #         a,b = b,a+b
    #         n += 1
    #     return 'done'
    # print(type(fib))
    def fib(max):       #函数生成器
        n,a,b = 0,0,1
        while max > n:
            # print(b)
            yield b
            a,b = b,a+b
            n += 1
        return 'done'
    print(type(fib(5)))
    for i in fib(5):
        print(i)
    
    ### 单线程并行效果
    import time
    def foo(name):
        print("%s 要开始吃包子了" %name)
        while True:
            baozi = yield
            print("包子 %s 被 %s 吃了" %(baozi,name))
    
    def war():
        a1 = foo('A')
        a2 = foo('B')
        a1.__next__()
        a2.__next__()
        print("我要准备做包子啦...")
        for i in range(5):
            time.sleep(1)
            print("做了2个包子...")
            a1.send(i)
            a2.send(i)
    
    
    war()
    View Code

    3、迭代器

    # -*- coding:utf-8 -*-
    # Author:Wong Du
    
    '''
    迭代器
    定义:迭代器与生成器类似,属数据流对象
        可以直接作用于for循环的对象统称为可迭代对象:Iterable,如list、dict、set、tuple、str等
        可以被next()函数调用并不断返回下一个值的对象称为迭代器:Iterator,生成器是迭代器
    判断方法:
        from collections import Iterator    #导入Iterator模块
        from collections import Iterable    #导入Iterable模块
        print(isinstance(g,Iterable))    #判断g是否是一个可迭代对象
        print(isinstance(g,Iterator))    #判断g是否是一个迭代器
    生成迭代器:
        iter()方法可以把可迭代对象编程一个迭代器
        如:
            list = (1,2,3,4)
            list = iter(list)
    '''
    
    ### 判断是否为迭代器或可迭代对象的方法
    from collections import Iterator
    from collections import Iterable
    str = '111'
    print(isinstance(str,Iterable))    #True
    print(isinstance(str,Iterator))    #False
    list = [1,2,3]
    print(isinstance(list,Iterable))    #True
    print(isinstance(list,Iterator))    #False
    g = (i*2 for i in range(5))
    print(isinstance(g,Iterable))    #True
    print(isinstance(g,Iterator))    #True
    
    
    ### 可迭代对象可通过iter()方法变成一个迭代器
    tup = (1,2,3,4,5,4)
    print(type(tup))        #tuple
    tup = iter(tup)
    print(type(tup))        #tuple_iterator
    View Code

    4、内置方法

    # -*- coding:utf-8 -*-
    # Author:Wong Du
    
    def dir_object():
        ## 删除对象的属性方法
        ## delattr(object, name: str)
        delattr('Wong', 'count')
    
        ## 判断对象是否有这个属性方法
        ## hasattr(object, name: str)
        print(hasattr('Wong', 'count1'))
    
        ## 获取对象的属性方法,如存在可直接调用执行,如不存在则可配置default返回相关信息
        ## getattr(object, name: str, default)
        print(getattr('Wong,ggg', 'count', '不存在'))
    
        ## 为对象添加属性方法
        ## setattr(object, name: str, value)
        def Wong(name):  # 定义函数对象
            print("Welcome to", name)
            print("I am 23 years old")
            return 'done'
        setattr(Wong, 'author', 'Wongdu')  # 增加'author'属性
        print(hasattr(Wong, 'author'))  # 验证
    
    # 绝对值,
    # abs(n),Return the absolute value of the argument.
    print( abs(-22) )
    
    # 判断可迭代对象内元素是否全为真
    # all(Iterable)
    '''Return True if bool(x) is True for all values x in the iterable.
    If the iterable is empty, return True.'''
    print( all([1,2,3,0]) )
    
    # 判断可迭代对象内元素是否有真
    # any(Iterable)
    '''Return True if bool(x) is True for any x in the iterable.
    If the iterable is empty, return False.'''
    print( any([1,'0','']) )
    
    # 把对象变成可打印的字符串形式,如存在中文字符,则用二进制表示;repr则所见即所得
    # ascii(object);repr(object)
    print(ascii({'name':'wong','age':23,'您好':''}))
    print([repr([1,2,3,'22','您好'])])
    
    # 把int对象转换成二进制
    # bin(number:int)
    '''Return the binary representation of an integer.'''
    print( bin(256) )
    
    # 判断对象是否可调用,如函数是可调用的
    # callable(object)
    def calla():print("It is callable...")
    print( callable(calla) )
    
    # 使用序号i返回一个字符的Unicode字符串
    # chr(i)
    print(chr(1111))
    
    # 打印给定对象的所有方法
    # dir(object)
    print( dir([1,2,3]) )
    
    # 返回一个元组,关系:((x-x%y)/y, x%y)
    # divmod(number,numbre)
    print( divmod(22.22,23) )
    
    #退出程序
    import time
    time.sleep(1)
    exit("退出程序")
    
    # 为集合体元素进行编号一一对应
    dict = {'name':'Wong','age':23,'sox':'man'}
    print(dict)
    for k,v in enumerate(dict):
        print(k,v,dict[v])
    
    # 在全局和本地语境中评估给定的源。
    #eval()
    
    # 在全局和本地语境中执行给定的源。
    #exec()
    
    # 格式化输出
    print("My name is {_name}".format(_name="Wong"))
    
    # 过滤可迭代对象中的元素生成一个迭代器
    s = filter(lambda x:x==1,range(10))  #
    print(s)
    for s1 in s:
        print(s1)
    
    # 对可迭代对象中的元素进行计算生成一个迭代器
    g = map(lambda x:x*5,range(10))
    print(g)
    for g1 in g:
        print(g1)
    
    
    # 返回包含当前作用域全局变量的字典
    print(globals())
    # 返回包含当前作用域局部变量的字典
    print(locals())
    # 没有参数时,返回当前作用域局部变量的字典,相当于locals()
    print(vars())
    
    # 返回一个对象的哈希值
    # hash(object)
    list = []
    for i in ['1','666','2','3','45',33]:
        print(hash(i))
        list.append(hash(i))
    list.sort()
    print(list)
    
    # 查看帮助
    # help(object)
    help(dict)
    
    # 返回int对象的16进制
    # hex(int)
    print(hex(111))
    
    # 判断对象是否属于哪个类型
    # isinstance(object,union)
    print(isinstance('11',int))
    from collections import Iterator,Iterable
    print(isinstance('asdfg',Iterable))
    print(isinstance('asdfg',Iterator))
    
    # 用户输入
    # input()
    name = input("您的名字是:")
    print(name)
    
    # 返回对象的内存地址
    # id(object)
    print(id('name'))
    
    # 把可迭代对象变成迭代器
    # iter(iterable)
    list = [1,2,34,5]
    list = iter(list)
    print(list)
    
    # 计算集合体的长度
    # len(list)等,可迭代对象?
    print(len({'name':"wong",'age':23}))
    
    # 版本作者等信息
    copyright()
    credits()
    license()
    
    # 取可迭代对象中的最大值
    # max(Iterable)
    print(max({'name':'wong','age':23}))
    
    # 取可迭代对象中的最小值
    # min(Iterable)
    print(min({'name':'wong','age':23}))
    
    # 打开文件
    # open(file,mode,encoding)
    f = open('test','r')
    f.close()
    
    # 返回int对象的八进制表示
    # oct(int)
    print(oct(64))
    
    # 通过单个字符,返回ascii表的对应编号
    # ord(str)
    print(ord('@')
    
    # 打印内容
    # print("你想表达的内容")
    print("打印")
    
    # 按如下公式计算
    # Equivalent to x**y (with two arguments) or x**y % z (with three arguments)
    # pow(int, int, *int)
    print(pow(2,8,127))
    
    # 退出程序,指定退出程序code
    # quit(code)
    count = 0
    while True:
        print("你是风儿我是沙,缠缠绵绵走天涯...")
        if count >1000:
            quit(4)
        count += 1
    
    # 反转集合体内元素并生成一个迭代器
    # reversed(sequence)
    rev_iter = reversed([1,2,33,4])
    print(rev_iter)
    for _i in rev_iter:
        print(_i)
    
    # 设置数字的精确位,会四舍五入算法
    # round(number, ndigits=None)
    print(round(23.266655555,5))
    
    # 排序可迭代对象内的元素
    # sorted(Iterable)
    print(sorted([1,2,44,5,66,7]))
    
    # 求和
    # sum(int)
    print(sum([1,2,3,44,5]))
    
    # 将多个可迭代对象的元素一一对应形成一个元组,生成一个迭代器,长度以最小元素的可迭代对象为准
    # zip(Iterable1,Iterable2,Iterable3...)
    print(zip([1,2,3,55,6]))
    for iz in zip([1,2,3,55,6],{'name':'wong','age':23}):
        print(iz)
    View Code

    5、可序列化

    # -*- coding:utf-8 -*-
    # Author:Wong Du
    
    '''
    序列化
    序列化可将非字符串的数据类型的数据进行存档,如字典、列表甚至是函数等等
    反序列化,将通过序列化保存的文件反序列化即可得到数据原本的样子,可直接使用
    python中序列化的方式:
        json:只可序列化简单的数据类型,如字典、列表等,其他语言也有json,即json可跨语言进行序列和反序列化
        pickle:python独有的序列化,可序列化一切数据,以二进制的形式保存
        python中json和pickle的用法基本上是一模一样的
    '''
    
    dict = {'name':'wong','age':'23'}
    
    # with open('test','w') as f:
    #     f.write(dict)
    ### 报错:TypeError: write() argument must be str, not dict
    
    
    '''
    ### 把字典用json序列化后写入文件
    ### json.dumps(obj); json.dump(obj, fp)
    ### f.write(json.dumps(dict)) == json.dump(dict,f)
    '''
    import json
    with open('test','w') as f:
        # f.write(json.dumps(dict))
        json.dump(dict,f)
    ### 成功写入
    
    '''pickle序列化'''
    import pickle
    def foo():
        print("In the foo...")
    foo()
    with open('test2','wb') as f:       #以二进制字节类型写入到文件当中,所以mode = 'wb'
        # f.write(pickle.dumps(foo))
        pickle.dump(foo,f)
    ### 写入成功!注意,这里的写入是把foo函数对象写入到文件当中,反序列化后,当代码里没有foo函数对象,则会报错
    
    
    list = [1,2,3,4,'name']
    with open('test3','wb') as f:
        # f.write(pickle.dumps(list))
        pickle.dump(list,f)
    序列化
    # -*- coding:utf-8 -*-
    # Author:Wong Du
    
    '''
    序列化
    序列化可将非字符串的数据类型的数据进行存档,如字典、列表甚至是函数等等
    反序列化,将通过序列化保存的文件反序列化即可得到数据原本的样子,可直接使用
    python中序列化的方式:
        json:只可序列化简单的数据类型,如字典、列表等,其他语言也有json,即json可跨语言进行序列和反序列化
        pickle:python独有的序列化,可序列化一切数据,以二进制的形式保存
    '''
    
    # with open('test','r') as f:
    #     print(f.read())
    #     f.read()['name']
    ### 报错:TypeError: string indices must be integers
    
    '''
    ### json反序列化读取文件内容,可直接获取到字典,进行元素调用
    ### json.loads(str); line = json.load(fp)
    ### line = json.loads(f.read()) == line = json.load(f)
    '''
    import json
    with open('test','r') as f:
        # line = json.loads(f.read())
        line = json.load(f)
        print(type(line))
        print(line['age'])
    ### 成功调用
    '''
    输出:
    <class 'dict'>
    23
    '''
    
    
    import pickle
    def foo():
        print("In the foo2...")
    with open('test2','rb') as f:       #以二进制字节类型读取文件内容,所以mode = 'rb'
        # line = pickle.loads(f.read())
        line = pickle.load(f)
        line()
    
    
    with open('test3','rb') as f:
        # line = pickle.loads(f.read())
        line = pickle.load(f)
        print(type(line))
        print(line[4])
    反序列化

    6、项目规范化

     1 App/
     2     bin/
     3         app
     4     conf
     5         conf.py
     6     app
     7         test
     8             __init__.py
     9             main.py
    10         main.py
    11         __init__.py
    12     setup.py
    13     requirement.txt
    14     readme/README
    静静的学习一阵子儿...
  • 相关阅读:
    漫谈C语言结构体
    如何理解c和c++的复杂类型声明
    STM32 时钟系统
    STM32 系统架构
    运放参数的详细解释和分析-part1,输入偏置电流和输入失调电流【转】
    ROM、RAM、DRAM、SRAM、FLASH的区别?
    FATFS模块应用笔记
    关于I2C和SPI总线协议【转】
    USB编程概念
    Ubuntu手机识别
  • 原文地址:https://www.cnblogs.com/Caiyundo/p/8527033.html
Copyright © 2011-2022 走看看