zoukankan      html  css  js  c++  java
  • 装饰器2decorator

    装饰器添加参数传递:

     1 import time
     2 # 高阶函数深入
     3 
     4 
     5 def bar1():
     6     print('Begin to sleep')
     7     time.sleep(2)
     8     print('In the bar1')
     9     return 0
    10 
    11 
    12 def bar2():
    13     print('Begin to sleep')
    14     time.sleep(3)
    15     print('In the bar2')
    16     return 0
    17 
    18 
    19 def test(func):  # 定义装饰器
    20     print(func)
    21 # 上面打印的是函数的地址,即储存内容的‘门牌号’
    22     func()  # 运行函数的内容
    23     return func  # 返回参数函数,使参数函数的调用方式不变
    24 
    25 
    26 bar1 = test(bar1)
    27 bar1()  #参数函数的调用方式不变
    28 # 下面设计装饰器,计算test1、test2的运行时间
    29 def timer(func):
    30     def deco(*args, **kwarge):  # *args, **kwarge:表示非固定参数,灵活变通
    31         start_time = time.time()
    32         func(*args, **kwarge)  # 在函数的参数里面需要带相应的*、**
    33         stop_time = time.time()
    34         print('The func running time is %s' % (stop_time - start_time))
    35         return 0
    36     return deco
    37 
    38 
    39 @timer  #相当于test1=timer(test1)
    40 def test1():
    41     print('Begin to sleep')
    42     time.sleep(2)
    43     print('In the test1')
    44     return 0
    45 
    46 @timer
    47 def test2(name, age, **kwarge):
    48     print(name)
    49     print(age)
    50     print(kwarge)  # 实际输出时不能带相应的*、**
    51     return 0
    52 
    53 
    54 print('Decorator2 begins to run!')
    55 test1()  #因为第40行有@timer,所以可以直接用
    56 test2("Flagon", 33, Height='173cm', Gender='Male')
    View Code

     这是Python语言,开始忘记选了,默认是c#

  • 相关阅读:
    jdbc练习demo
    需登录账号与密码的网页爬取demo
    获取中文的首字母demo
    短信发送接口demo
    读取配置文件工具demo
    省选模拟96
    省选模拟95
    省选模拟94
    省选模拟92
    省选模拟91
  • 原文地址:https://www.cnblogs.com/gzj137070928/p/13703796.html
Copyright © 2011-2022 走看看