zoukankan      html  css  js  c++  java
  • 函数

    知识点
    1.闭包函数--requests 请求模块
     1 '''
     2 闭包函数:
     3   1.闭:定义在函数内部的函数
     4   2.包:内部函数引用了外部作用域的名字
     5 
     6 '''
     7 '''
     8 # inner 闭包函数 
     9     1.定义在outter函数内部,
    10     2.内部函数引用了外部作用域的名字
    11     例:print(x)引用  x = 111
    12 # 代码运行顺序
    13 def outter():  # 1  # 3
    14     x = 111  # 4
    15     def inner():  # 5  # 9
    16         print(x)  # 10
    17     return inner  # 函数的复制 代表inner函数 所以它就是一个闭包:一个被动态创建的可以记录外部变量的函数。 # 6
    18 res = outter() # res 就是inner内存的地址  # 2 函数调用优先级最高,进入函数outter  # 7
    19 res() #  8  #11   # 值 <function outter.<locals>.inner at 0x000001A3F8D798C8>
    20 print(res) # 12   # 值 111
    21 
    22 '''
    23 '''
    24 # 两种给函数传参的方式:
    25 # 1.给函数体传参的第一种方式   ----  普通传参
    26 def index(username):
    27     print(username)
    28 # 2.给函数体传参的第二种方式   ----   闭包函数传参
    29 # 函数内部自定义
    30 def ourtter():
    31     x = 1
    32     y = 40
    33     def my_max():
    34         if x > y:
    35             return x
    36         return y
    37     return my_max
    38 res = ourtter()
    39 res()
    40 print(res)  # <function ourtter.<locals>.my_max at 0x000001706D229950> # res 表示 my_max内存的地址
    41 print(res())  # 40  # 调用函数
    42 print('----------------------------------------------------------------------')
    43 # 闭包函数传参--直接传给装饰器
    44 def ourtter(x,y):
    45     def my_max():
    46         if x > y:
    47             return x
    48         return y
    49     return my_max
    50 res = ourtter(1,40)
    51 res()
    52 print(res)  # <function ourtter.<locals>.my_max at 0x000001706D229950> # res 表示 my_max内存的地址
    53 print(res())  # 40  # 调用函数
    54 '''
    55 # 两种传参方式的实际应用
    56 
    57 # 星轨
    58 
    59 import requests
    60 # 第一直接给函数传参
    61 url1 = 'https://www.baidu.com'
    62 url2 = '...'
    63 def my_get_web(url):  #     response :响应 = requests:请求.get(url)
    64     response = requests.get(url)  # status_code :状态码 == 200 : OK :
    65     if response.status_code == 200:
    66         print(len(response.text))   # 2443
    67         print(response.text)   # 前端html语眼标签
    68 my_get_web(url1)
    69 # 闭包函数传参----传给装饰器
    70 def outter(url): # 相当于,下边自定义# url = 'https://www.jd.com'
    71     # url = 'https://www.jd.com'
    72     def my_get_web():
    73         response = requests.get(url)
    74         if response.status_code == 200:
    75             print(len(response.text))
    76     return my_get_web
    77 res = outter('https://www.baidu.com')
    78 res() # 2443
    闭包函数知识点

    2.装饰器--time模块
    ------可调用函数callable ------------- 皆可被装饰
     1 '''
     2 闭包函数:
     3   1.闭:定义在函数内部的函数
     4   2.包:内部函数引用了外部作用域的名字
     5 
     6 '''
     7 '''
     8 # inner 闭包函数 
     9     1.定义在outter函数内部,
    10     2.内部函数引用了外部作用域的名字
    11     例:print(x)引用  x = 111
    12 # 代码运行顺序
    13 def outter():  # 1  # 3
    14     x = 111  # 4
    15     def inner():  # 5  # 9
    16         print(x)  # 10
    17     return inner  # 函数的复制 代表inner函数 所以它就是一个闭包:一个被动态创建的可以记录外部变量的函数。 # 6
    18 res = outter() # res 就是inner内存的地址  # 2 函数调用优先级最高,进入函数outter  # 7
    19 res() #  8  #11   # 值 <function outter.<locals>.inner at 0x000001A3F8D798C8>
    20 print(res) # 12   # 值 111
    21 
    22 '''
    23 '''
    24 # 两种给函数传参的方式:
    25 # 1.给函数体传参的第一种方式   ----  普通传参
    26 def index(username):
    27     print(username)
    28 # 2.给函数体传参的第二种方式   ----   闭包函数传参
    29 # 函数内部自定义
    30 def ourtter():
    31     x = 1
    32     y = 40
    33     def my_max():
    34         if x > y:
    35             return x
    36         return y
    37     return my_max
    38 res = ourtter()
    39 res()
    40 print(res)  # <function ourtter.<locals>.my_max at 0x000001706D229950> # res 表示 my_max内存的地址
    41 print(res())  # 40  # 调用函数
    42 print('----------------------------------------------------------------------')
    43 # 闭包函数传参--直接传给装饰器
    44 def ourtter(x,y):
    45     def my_max():
    46         if x > y:
    47             return x
    48         return y
    49     return my_max
    50 res = ourtter(1,40)
    51 res()
    52 print(res)  # <function ourtter.<locals>.my_max at 0x000001706D229950> # res 表示 my_max内存的地址
    53 print(res())  # 40  # 调用函数
    54 '''
    55 # 两种传参方式的实际应用
    56 
    57 # 星轨
    58 
    59 import requests
    60 # 第一直接给函数传参
    61 url1 = 'https://www.baidu.com'
    62 url2 = '...'
    63 def my_get_web(url):  #     response :响应 = requests:请求.get(url)
    64     response = requests.get(url)  # status_code :状态码 == 200 : OK :
    65     if response.status_code == 200:
    66         print(len(response.text))   # 2443
    67         print(response.text)   # 前端html语眼标签
    68 my_get_web(url1)
    69 # 闭包函数传参----传给装饰器
    70 def outter(url): # 相当于,下边自定义# url = 'https://www.jd.com'
    71     # url = 'https://www.jd.com'
    72     def my_get_web():
    73         response = requests.get(url)
    74         if response.status_code == 200:
    75             print(len(response.text))
    76     return my_get_web
    77 res = outter('https://www.baidu.com')
    78 res() # 2443
    装饰器知识点
    3.面条版购物车
      1 import os
      2 '''
      3 购物车:
      4 1.注册
      5 2.登录
      6 3.购物
      7 '''
      8 # 用户登录状态
      9 user_info = {
     10     'name':None,
     11     'pwd':None,
     12     'money':None,
     13 }
     14 # 商品列表
     15 shopp_list = [
     16     ['电动车',3496],
     17     ['纯牛奶',79],
     18     ['特步跑鞋',599],
     19     ['火腿',25],
     20 ]
     21 # 购物车
     22 shopp_cart = {
     23 
     24 }
     25 
     26 # 功能
     27 # 1.注册
     28 def register():
     29     while True:
     30         name = input('user>>>:').strip()
     31         if os.path.exists(f'{name}.txt'):
     32             print('用户已存在')
     33             continue
     34         else:
     35             pwd = input('pwd>>>:').strip()
     36             re_pwd = input('re_pwd>>>:').strip()
     37             if pwd == re_pwd:
     38                 res = ','.join([name, pwd, '15000'])
     39                 with open(f'{name}.txt', 'w', encoding='utf-8') as f:
     40                     f.write(res)
     41                     f.flush()
     42 
     43                 print('register True!')
     44                 break
     45 
     46             else:
     47                 print('pwd is False!')
     48 # 装饰器
     49 from functools import wraps
     50 def login_auth(func):
     51     @wraps(func)
     52     def inner(*args,**kwargs):
     53         if user_info['name'] :
     54             print('111111111111111')
     55             res = func(*args, **kwargs)
     56             print('自动登录')
     57             return res
     58         else:
     59             print('未登录,请录入信息')
     60             res = login()
     61             return res
     62     return inner
     63 
     64 # 2.登录
     65 def login():
     66     while True:
     67         name = input('user>>>:').strip()
     68         if os.path.exists(f'{name}.txt'):
     69             with open(f'{name}.txt', 'r', encoding='utf-8') as f:
     70                 res = f.read()
     71                 f_name, f_pwd, f_money = res.split(',')
     72                 if name == f_name:
     73                     print('用户输入正确')
     74                     pwd = input('pwd>>>:').strip()
     75                     if pwd == f_pwd:
     76                         print('登陆成功')
     77                         # 保存用户登录状态
     78                         user_info['name'] = name
     79                         user_info['pwd'] = pwd
     80                         # money 是 整型,f_money 是字符串类型
     81                         user_info['money'] = int(f_money)
     82                         break
     83                     else:
     84                         print('密码错误')
     85                 else:
     86                     print('用户名称输入错误')
     87         else:
     88             print('文件存在')
     89             continue
     90 # 3.购物
     91 @login_auth
     92 def go_shopping():
     93     print('合理消费,欢乐购物')
     94     # 消费总金额
     95     moneyes = 0
     96     while True:
     97         print('购物功能')
     98         # 清空购物车
     99         # 方法 : 结账
    100         # 判断是否有消费
    101         if moneyes:
    102             buy_shap = input('is_buy(y/n)').strip()
    103             if buy_shap == 'y':
    104                 # 付钱
    105                 user_info['money'] -= moneyes
    106                 # 存储到文件中,及时更新金额
    107                 user_info['money'] = str(user_info['money'])
    108                 res = ','.join([user_info['name'], user_info['pwd'], user_info['money']])
    109 
    110                 with open(f'{user_info["name"]}.txt', 'w', encoding='utf-8') as f:
    111                     f.write(res)
    112                     f.flush()
    113 
    114                 moneyes = 0
    115 
    116                 print('购物成功!')
    117                 break
    118             else:
    119                 print('不了,我再看看')
    120                 # 打印购物车
    121                 for k,v in shopp_cart.items():
    122                     print(k,v)
    123                     # 1.指定pop
    124                     # 2.全部清空clear
    125         else:
    126             print('购物车为空,快点去商城逛逛吧')
    127 
    128         # 打印商品列表
    129         # enumerate多用于在for循环中得到计数,利用它可以同时获得索引和值,即需要index和value值的时候可以使用
    130 
    131         for k,v in enumerate(shopp_list,start=1):
    132             print(k,v)
    133 
    134         # 用户选择商品编号
    135         choose = input('please choose:').strip()
    136         if choose == 'q':
    137             print('退出')
    138             break
    139 
    140         # 若果是数字  .isdigit():判断是否是整型
    141         if choose.isdigit():
    142             choose = int(choose)
    143             if choose in range(1,len(shopp_list)+1):
    144                 shapig = shopp_list[choose-1][0]
    145                 price = shopp_list[choose-1][1]
    146 
    147 
    148 
    149                 # 判断金额是否足够
    150                 print(type(user_info['money']))
    151                 if user_info['money'] >= price:
    152 
    153                     print('加入购物车{shapig}')
    154                     # 添加购物车
    155                     if shapig in shopp_cart:
    156                         # 在加一件
    157                         shopp_cart[shapig] += 1
    158                     else:
    159                         # 没有该产品
    160                         shopp_cart[shapig] = 1
    161                     # 得到支付金额
    162                     moneyes += price
    163                 else:
    164                     print('余额不足')
    165             else:
    166 
    167                 print('please number')
    168                 continue
    169 
    170 
    171 # 映射
    172 func_dic ={
    173     '1':register,
    174     '2':login,
    175     '3':go_shopping,
    176 }
    177 # 主功能
    178 def run():
    179     print('欢迎光临淘宝!')
    180     while True:
    181         print("""1.注册
    2.登录
    3.购物车
    """)
    182         choose = input('please choose>>>:').strip()
    183         if choose == 'q':
    184             print('退出,quit')
    185             break
    186         elif choose in func_dic:
    187             func_dic[choose]()
    188         else:
    189             print('please again input!')
    190 
    191 if __name__ == "__main__":
    192     run()
    购物车--面条版
    
    

     4.小知识点

     1 """
     2 本节涉及小知识点
     3 1.小爬虫 requests 模块
     4   本质:1.爬取页面的html代码,2.从中获取到你想要的数据(url链接地址)
     5         3.有了链接之后 你就可以顺着这个链接将所有的页面资源全部爬取下来
     6 
     7 2.时间戳 time 模块
     8  应用:统计函数运行时间
     9     import time
    10     time.time()  获取时间戳(秒)    当前时间距离1970 1.1 00:00:00 所进过的秒数
    11     time.sleep(seconds)  让程序暂定几秒钟
    12 
    13 """
    小爬虫-requests time 时间模块
     1 """
     2 本节涉及小知识点
     3 1.小爬虫 requests 模块
     4   本质:1.爬取页面的html代码,2.从中获取到你想要的数据(url链接地址)
     5         3.有了链接之后 你就可以顺着这个链接将所有的页面资源全部爬取下来
     6 
     7 2.时间戳 time 模块
     8  应用:统计函数运行时间
     9     import time
    10     time.time()  获取时间戳(秒)    当前时间距离1970 1.1 00:00:00 所进过的秒数
    11     time.sleep(seconds)  让程序暂定几秒钟
    12 
    13 """
    小爬虫-requests time 时间模块



    详解:

    '''
    1.闭包函数:
    1.闭:定义在函数内部的函数
    2.包:内部函数引用了外部函数作用域的名字
    '''
    1 def outter():
    2     x = 111
    3     def inner():
    4         print(x)
    5     return inner
    6 res = outter()
    7 res()
    8 # print(res())
    9 print(res.x)
    闭包函数
    """
    2.装饰器:
    器:工具
    装饰:给装饰对象添加新的功能
    可调用对象都可被装饰
    使用装饰器的原因:
    开放封闭原则:
    开放:对扩展开放
    封闭:对(原功能)修改封闭
    原因一:再不改变原功能的基础上,添加新的功能

    装饰器必须遵循原则
    1.不改变被装饰对象源代码
    2.不改变被装饰对象调用方式
    def index():
    pass
    index()
    """
    装饰器的推导
    1.装饰器的简单版本
     1 """
     2 1.统计index函数的执行的时间
     3 """
     4 import time
     5 
     6 # 被装饰的对象
     7 def index():  # 1   # 12
     8     time.sleep(3)   # 13
     9     print('打字数据')  # 14
    10 
    11 # 装饰器
    12 # 被装饰函数传参----传值给装饰函数 outter()
    13 def outter(func):  # 2  # 4
    14     def get_time():  # 5  # 9
    15         start = time.time()  # 10
    16         func()  # fun = index函数的内存地址()  # 调用的是最原始 index() 函数  # 11  #15
    17         end = time.time()
    18         print('cpu处理时间(index函数的执行的时间)',end-start)  # 16
    19     return get_time  # 是对闭包函数的复制  # 6
    20 res = outter(index)  # index 传的是最原始的index()  # 3   # 7
    21 res() # 相当于get_time 函数 # 8  # 17
    22 
    23 #
    24 '''
    25 打字数据
    26 cpu处理时间(index函数的执行的时间) 3.0010035037994385
    27 '''
    装饰器的简单版
    2.装饰器的升级版---(1.有参 2.无参)------被装饰器
     1 """
     2 1.统计index函数的执行的时间
     3 """
     4 import time
     5 # 被装饰函数 1.有参 2. 无参
     6 # 1.无参
     7 def index():
     8     time.sleep(3)
     9     print('呜啊哈哈哈')
    10 
    11 #2. 有参
    12 def login(name,pwd):
    13     print('%s'%name)
    14     print('%s'%pwd)
    15     # name = input('name:').strip()
    16     # pwd = input('pwd:').strip()
    17     if name == 'llx' and pwd == '123':
    18         print('登陆成功')
    19 
    20 # 装饰器
    21 def outter(func):
    22     def inner(*args,**kwargs):
    23         start = time.time()
    24         res = func(*args,**kwargs)
    25         end = time.time()
    26         print('cpu处理时间(index函数的执行的时间)',end-start)
    27         return res
    28     return inner
    29 # 无参
    30 # res = outter(index)
    31 # res()
    32 #
    33 # 呜啊哈哈哈
    34 # cpu处理时间(index函数的执行的时间) 3.000974416732788
    35 
    36 # 有参
    37 login = outter(login)
    38 # 传参(最原始index传参)
    39 res = login('llx','123')
    40 res()
    41 '''
    42 值:
    43 llx
    44 123
    45 登陆成功
    46 cpu处理时间(index函数的执行的时间) 0.0
    47 '''
    装饰器的升级版
    3.装饰器的语法糖
     1 # 格式
     2 import time
     3 
     4 def outter(func):  # index = outter(index)  # 传入最原始的index(被调用对像,即被装饰对象)
     5     def inner(*args,**kwargs):
     6         start = time.time()
     7         res = func(*args,**kwargs)
     8         end = time.time()
     9         print('cpu处理时间(index函数的执行的时间)',end-start)
    10         return res # 调用最原始的index(被装饰对象)
    11     return inner
    12 
    13 @outter  # index = outter(index)  # @outter语法,自动调用他下边的函数
    14 def index():
    15     time.sleep(3)
    16     print('好无聊')
    17     # return 'index'   # 'index'和index无名显区别
    18     return index
    19 # index()
    20 #   值 好无聊   cpu处理时间(index函数的执行的时间) 3.000035285949707
    21 
    22 @outter  # login = outter(login)
    23 def login(name):
    24     time.sleep(1)
    25     print('%s is sb'%name)
    26     return 'login'
    27 # res = login('egon')
    28 #
    29 '''
    30 egon is sb
    31 cpu处理时间(index函数的执行的时间) 1.000326156616211
    32 '''
    33 @outter  # home = outter(home)
    34 def home(*args,**kwargs):
    35     time.sleep(1)
    36     return 'home'
    37 home()  # 值 cpu处理时间(index函数的执行的时间) 1.0003252029418945
    装饰器的语法糖
    4.装饰器的模板
     1 # 模板
     2 def outter(func):
     3     def inner(*args,**kwargs):
     4         print('执行被装饰函数之前 你可做的操作')
     5         res = func(*args,**kwargs)
     6         print('执行被装饰函数之后 你可做的操作')
     7 
     8         return res
     9     return inner
    10 """
    11 认证装饰器
    12     执行函数index之前必须先输入用户名和密码,正确后,才能执行index
    13     否则提示用户输入错误 结束程序
    14 """
    15 from functools import wraps
    16 def login_auth(func):
    17     @wraps(func)
    18     def inner(*args,**kwargs):
    19         print('wyf,sb')
    20         res = func(*args,**kwargs)
    21         print('llx,大帅比')
    22         return res
    23     return inner
    24 
    25 @login_auth
    26 def login():
    27     name = input('plesae user>>>:').strip()
    28     pwd = input('please pwd>>>:').strip()
    29     if name == 'llx' and pwd == '123':
    30         print('登陆成功')
    31     else:
    32         print('账户或密码输入错误')
    33     return '登陆成功'
    34 
    35 login()
    36 """
    37 值:
    38 wyf,sb
    39 plesae user>>>:llx
    40 please pwd>>>:123
    41 登陆成功
    42 llx,大帅比
    43 """
    装饰器的模板--自己写的认证装饰器
    5.认证装饰器--老师的版本
     1 """
     2 1.统计index函数的执行的时间
     3 """
     4 import time
     5 
     6 # 被装饰的对象
     7 def index():  # 1   # 12
     8     time.sleep(3)   # 13
     9     print('打字数据')  # 14
    10 
    11 # 装饰器
    12 # 被装饰函数传参----传值给装饰函数 outter()
    13 def outter(func):  # 2  # 4
    14     def get_time():  # 5  # 9
    15         start = time.time()  # 10
    16         func()  # fun = index函数的内存地址()  # 调用的是最原始 index() 函数  # 11  #15
    17         end = time.time()
    18         print('cpu处理时间(index函数的执行的时间)',end-start)  # 16
    19     return get_time  # 是对闭包函数的复制  # 6
    20 res = outter(index)  # index 传的是最原始的index()  # 3   # 7
    21 res() # 相当于get_time 函数 # 8  # 17
    22 
    23 #
    24 '''
    25 打字数据
    26 cpu处理时间(index函数的执行的时间) 3.0010035037994385
    27 '''
    认证装饰器--老师的版本
    6.实际购物车中装饰器的应用
      1 import os
      2 '''
      3 购物车:
      4 1.注册
      5 2.登录
      6 3.购物
      7 '''
      8 # 用户登录状态
      9 user_info = {
     10     'name':None,
     11     'pwd':None,
     12     'money':None,
     13 }
     14 # 商品列表
     15 shopp_list = [
     16     ['电动车',3496],
     17     ['纯牛奶',79],
     18     ['特步跑鞋',599],
     19     ['火腿',25],
     20 ]
     21 # 购物车
     22 shopp_cart = {
     23 
     24 }
     25 
     26 # 功能
     27 # 1.注册
     28 def register():
     29     while True:
     30         name = input('user>>>:').strip()
     31         if os.path.exists(f'{name}.txt'):
     32             print('用户已存在')
     33             continue
     34         else:
     35             pwd = input('pwd>>>:').strip()
     36             re_pwd = input('re_pwd>>>:').strip()
     37             if pwd == re_pwd:
     38                 res = ','.join([name, pwd, '15000'])
     39                 with open(f'{name}.txt', 'w', encoding='utf-8') as f:
     40                     f.write(res)
     41                     f.flush()
     42 
     43                 print('register True!')
     44                 break
     45 
     46             else:
     47                 print('pwd is False!')
     48 # 装饰器
     49 from functools import wraps
     50 def login_auth(func):
     51     @wraps(func)
     52     def inner(*args,**kwargs):
     53         if user_info['name'] :
     54             print('111111111111111')
     55             res = func(*args, **kwargs)
     56             print('自动登录')
     57             return res
     58         else:
     59             print('未登录,请录入信息')
     60             res = login()
     61             return res
     62     return inner
     63 
     64 # 2.登录
     65 def login():
     66     while True:
     67         name = input('user>>>:').strip()
     68         if os.path.exists(f'{name}.txt'):
     69             with open(f'{name}.txt', 'r', encoding='utf-8') as f:
     70                 res = f.read()
     71                 f_name, f_pwd, f_money = res.split(',')
     72                 if name == f_name:
     73                     print('用户输入正确')
     74                     pwd = input('pwd>>>:').strip()
     75                     if pwd == f_pwd:
     76                         print('登陆成功')
     77                         # 保存用户登录状态
     78                         user_info['name'] = name
     79                         user_info['pwd'] = pwd
     80                         # money 是 整型,f_money 是字符串类型
     81                         user_info['money'] = int(f_money)
     82                         break
     83                     else:
     84                         print('密码错误')
     85                 else:
     86                     print('用户名称输入错误')
     87         else:
     88             print('文件存在')
     89             continue
     90 # 3.购物
     91 @login_auth
     92 def go_shopping():
     93     print('合理消费,欢乐购物')
     94     # 消费总金额
     95     moneyes = 0
     96     while True:
     97         print('购物功能')
     98         # 清空购物车
     99         # 方法 : 结账
    100         # 判断是否有消费
    101         if moneyes:
    102             buy_shap = input('is_buy(y/n)').strip()
    103             if buy_shap == 'y':
    104                 # 付钱
    105                 user_info['money'] -= moneyes
    106                 # 存储到文件中,及时更新金额
    107                 user_info['money'] = str(user_info['money'])
    108                 res = ','.join([user_info['name'], user_info['pwd'], user_info['money']])
    109 
    110                 with open(f'{user_info["name"]}.txt', 'w', encoding='utf-8') as f:
    111                     f.write(res)
    112                     f.flush()
    113 
    114                 moneyes = 0
    115 
    116                 print('购物成功!')
    117                 break
    118             else:
    119                 print('不了,我再看看')
    120                 # 打印购物车
    121                 for k,v in shopp_cart.items():
    122                     print(k,v)
    123                     # 1.指定pop
    124                     # 2.全部清空clear
    125         else:
    126             print('购物车为空,快点去商城逛逛吧')
    127 
    128         # 打印商品列表
    129         # enumerate多用于在for循环中得到计数,利用它可以同时获得索引和值,即需要index和value值的时候可以使用
    130 
    131         for k,v in enumerate(shopp_list,start=1):
    132             print(k,v)
    133 
    134         # 用户选择商品编号
    135         choose = input('please choose:').strip()
    136         if choose == 'q':
    137             print('退出')
    138             break
    139 
    140         # 若果是数字  .isdigit():判断是否是整型
    141         if choose.isdigit():
    142             choose = int(choose)
    143             if choose in range(1,len(shopp_list)+1):
    144                 shapig = shopp_list[choose-1][0]
    145                 price = shopp_list[choose-1][1]
    146 
    147 
    148 
    149                 # 判断金额是否足够
    150                 print(type(user_info['money']))
    151                 if user_info['money'] >= price:
    152 
    153                     print('加入购物车{shapig}')
    154                     # 添加购物车
    155                     if shapig in shopp_cart:
    156                         # 在加一件
    157                         shopp_cart[shapig] += 1
    158                     else:
    159                         # 没有该产品
    160                         shopp_cart[shapig] = 1
    161                     # 得到支付金额
    162                     moneyes += price
    163                 else:
    164                     print('余额不足')
    165             else:
    166 
    167                 print('please number')
    168                 continue
    169 
    170 
    171 # 映射
    172 func_dic ={
    173     '1':register,
    174     '2':login,
    175     '3':go_shopping,
    176 }
    177 # 主功能
    178 def run():
    179     print('欢迎光临淘宝!')
    180     while True:
    181         print("""1.注册
    2.登录
    3.购物车
    """)
    182         choose = input('please choose>>>:').strip()
    183         if choose == 'q':
    184             print('退出,quit')
    185             break
    186         elif choose in func_dic:
    187             func_dic[choose]()
    188         else:
    189             print('please again input!')
    190 
    191 if __name__ == "__main__":
    192     run()
    装饰器应用--购物车面条版
    7.知识提升--wraps:装饰器修复技术
     1 # 导入模块
     2 from functools import wraps
     3 # 使用
     4 def outter(func):
     5     @wraps(func)
     6     def inner(*args,**kwargs):
     7         res = func(*args,**kwargs)
     8         return res
     9     return inner
    10 """
    11 作用:被装饰的函数,查询注释认识本身,无法查知被装饰过
    12 """
    wraps--装饰器修复技术
    8.知识提升--多层装饰器
    多层装饰器:
    1.outte(func) index = outter(index) # 这里上传的是最原始index
    2.传给inner(*args,**kwargs)闭包函数,用res = func(*args,**kwargs)接收
    3.特殊请求需要给闭包函数传其他的参数,引入了多层装饰器,(其实也就三层)
    """
     1 from functools import wraps
     2 import time
     3 
     4 # 记录登录状态
     5 user_dic = {
     6     'is_login': None
     7 }
     8 
     9 # 正常装饰器
    10 def outter(func):
    11     @wraps(func)
    12     def inner(*args,**kwargs):
    13         start = time.time()
    14         res = func(*args,**kwargs)
    15         print('2-11111111111111111111111111')
    16         end = time.time()
    17         print('cpu处理时间:',end-start)
    18         return res
    19     return inner
    20 
    21 # 外围加装的这个装饰器是为了传输参数或者数据
    22 def login_auth2(data,x,y):
    23     # 装饰器传原始index函数
    24     def login_auth(func):
    25         # 闭包函数
    26         def inner(*args,**kwargs):
    27             if user_dic['is_login']:
    28                 # 原始 index()访问
    29                 res = func(*args,**kwargs)
    30                 print('3---1111111111111111111111111')
    31                 return res # 调用原始index函数
    32             else:
    33                 # 加装装饰器传参
    34                 # 数据来源
    35                 if data == 'file':
    36                     name = input('name:').strip()
    37                     pwd = input('pwd:').strip()
    38                     if name == 'llx' and  pwd == '123':
    39                         user_dic['is_login'] = True
    40                         res = func(*args,**kwargs)
    41                         return res
    42                     else:
    43                         print('name or pwd False!')
    44                 elif data == 'Mysql':
    45                     print('from mysql')
    46                 # LDAP是轻量目录访问协议
    47                 elif data == 'ldap':
    48                     print('ldap')
    49                 else:
    50                     print('无数据来源')
    51         return inner
    52     return login_auth
    53 
    54 # 运行顺序  从上往下
    55 # 传参顺序 从下往上
    56 # 装饰器在装饰的时候  顺序从下往上
    57 # 装饰器在执行的时候  顺序从上往下
    58 @login_auth2('file',1,2)
    59 # 导入原始index() ,即func()
    60 @outter
    61 def index():
    62     time.sleep(3)
    63     print('今天感觉还不错')
    64     return 666666666
    65 index()
    66 
    67 """
    68 # 值
    69 name:llx
    70 pwd:123
    71 今天感觉还不错
    72 2-11111111111111111111111111
    73 cpu处理时间: 3.000495672225952
    74 
    75 """
    多层装饰器
  • 相关阅读:
    centos crash debug
    go get Unknown SSL protocol error in connection to gopkg.in
    Tensorflow serving with Kubernetes
    Spring 集成 Swagger UI
    Docker Registry V2 Garbage Collection
    Docker Registry V2 with Nginx
    Zabbix磁盘性能监控
    Zabbix CPU utilization监控参数
    Windows挂载Gluster复制卷
    Redis持久化存储(三)
  • 原文地址:https://www.cnblogs.com/llx--20190411/p/11177138.html
Copyright © 2011-2022 走看看