zoukankan      html  css  js  c++  java
  • python中装饰器的使用

    看个例子:

    # 定义装饰器函数
    def log(func):
        """
        接受一个函数作为参数,并返回一个函数
        :param func:
        :return:
        """
        def wrapper(*args,**kwargs):
            """
            :param args:
            :param kwargs:
            :return:
            """
            print("call %s():"% func.__name__)
            return func(*args,**kwargs)
        return wrapper
    
    @log
    def now():
        print(time.strftime("%Y-%m-%d %H:%M:%S",time.localtime()))
    now()

    输出:

    call now():
    2020-04-04 22:51:23

    1、本来now()的功能只是打印时间,现在我们要增强now()功能,在这里我们把这种自己定义的log函数的方式叫做装饰器(decorator)

    def now():
        print(time.strftime("%Y-%m-%d %H:%M:%S",time.localtime()))

    2、本质上装饰器是返回函数的高阶函数,接受一个函数作为参数,并返回一个函数

    def log(func):
        """
        接受一个函数作为参数,并返回一个函数
        :param func:
        :return:
        """
        def wrapper(*args,**kwargs):
            """
            :param args:
            :param kwargs:
            :return:
            """
            print("call %s():"% func.__name__)
            return func(*args,**kwargs)
        return wrapper

    3、借助@语法

    log
    def now():
        print(time.strftime("%Y-%m-%d %H:%M:%S",time.localtime()))

    运行now():

    call now():
    2020-04-04 22:51:23

    这里相当于执行了now=log(now)

    在wrapper函数内,可以接受任意参数的调用,首先打印日志,后面再调用原始的函数

    博文参考:https://www.liaoxuefeng.com/wiki/1016959663602400/1017451662295584

    业精于勤而荒于嬉,勤劳一日,可得一日安眠;勤劳一生,可得幸福一生。因为,我们努力了;因为,天道酬勤。
  • 相关阅读:
    查看.NET Core源代码通过Autofac实现依赖注入到Controller属性
    序列化二叉树
    把二叉树打印成多行
    按之字形顺序打印二叉树
    对称的二叉树
    JDK源码阅读顺序
    二叉树的下一个结点
    删除链表中重复的结点
    链表中环的入口结点
    字符流中第一个不重复的字符
  • 原文地址:https://www.cnblogs.com/Mr-choa/p/12635015.html
Copyright © 2011-2022 走看看