zoukankan      html  css  js  c++  java
  • 进军装饰器2/3

    装饰器装饰不同函数的用法:

    在实际应用场景下,会存在多个不同的函数需要相同的装饰器进行装饰,例如有些函数不需要传参,而有些则需要传参且传的参数均不固定,这时如果装饰器不能通用则会报错无法继续往下执行,以下示例会说明并解决此问题:

    # -*-coding:utf-8-*-
    # _Author_:George
    import time
    
    def timer(test):
        def decorator(*args,**kwargs):
            start_time = time.time()
            test(*args,**kwargs)
            end_time = time.time()
            print("Running time is :%s"%(end_time-start_time))
        return decorator
    
    @timer
    def test1():
        time.sleep(0.5)
        print("I'm test1")
    @timer
    def test2(name,age):
        time.sleep(1)
        print("I'm test2",name,age)
    test1()
    test2("George",5)

    此例子中其实考察了对函数传参的灵活用法。为帮助尚未掌握或仍不清楚函数传参的读者重审函数传参如下:

    当函数的参数不确定时,可以使用*args 和**kwargs,*args 没有key值,**kwargs有key值。

    *args 用来将参数打包成tuple给函数体调用;

    **kwargs 打包关键字参数成dict给函数体调用;

    *args 示例1:

    def function(*args):
        print(args, type(args))
    function(1)

    输出:
    (1,) <class 'tuple'>

    *args 示例2:

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

    输出:
    1 2 (3, 4, 5)

    **kwargs 示例1:

    def function(**kwargs):
        print( kwargs, type(kwargs))
    function(a=2)

    输出:
    {'a': 2} <class 'dict'>

    **kwargs 示例2:

    def function(**kwargs):
        print(kwargs)
    function(a=1, b=2, c=3, d=5)

    输出:
    {'a': 1, 'b': 2, 'c': 3, 'd': 5}
  • 相关阅读:
    西门子SCL读写DB数据
    LeetCode8.字符串转换整数(atoi) JavaScript
    LeetCode8.字符串转换整数(atoi) JavaScript
    WebRequestSugar
    iosblock用法
    datasci
    UINavigationController学习笔记
    iOSTab bar
    自定义tab bar控件 学习资料
    Ios tab Bar 使用方法
  • 原文地址:https://www.cnblogs.com/wangcx/p/8215797.html
Copyright © 2011-2022 走看看