zoukankan      html  css  js  c++  java
  • Python

    【原创】转载请注明作者Johnthegreat和本文链接

    关于装饰器的理解,特别像《盗梦空间》中的进入梦境和从梦境出来的过程,一层一层的深入梦境,然后又一层一层的返回,被带入梦境的是被装饰的函数,装饰器就是使人入梦的工具。

    上代码:

    from functools import wraps
    
    
    def decorator_with_argument(argument=''):
        def outer(func):
            message = argument + func.__name__
    
            @wraps(func)
            def inner(*args, **kwargs):
                print(message)
                print('This is inner function running')
                return func(*args, **kwargs)
    
            return inner
    
        return outer

    以上是装饰器的部分。

    接下来,是带参数的装饰器:

    @decorator_with_argument("Decorator's argument + ")
    def pfunc(arg='default'):
        print('This is pfunc running')
        print(f'This " {arg} " is from pfunc argument')
    

    最后,函数的运行:

    pfunc("pfunc's argument")

    函数本身也是带参数的。输出结果如下:

    Decorator's argument + pfunc
    This is inner function running
    This is pfunc running
    This " pfunc's argument " is from pfunc argument

    Process finished with exit code 0

    下图是关于梦境的具体图示:

    20200422231958

    如果你也有关于装饰器的有趣的描述,或者对于装饰器有不同的理解,欢迎交流。

  • 相关阅读:
    并发运行的思维模型
    进程和线程的区别
    拿来主义
    同步组件合作和团队合作 让世界变得更美好
    strace a++;b++;a+b;
    System 88: GDB Overview
    numpy多维数组维度及添加轴的理解
    Numpy入门
    python列表list 和numpy.array区别
    数组的生成方法
  • 原文地址:https://www.cnblogs.com/johnthegreat/p/12757750.html
Copyright © 2011-2022 走看看