zoukankan      html  css  js  c++  java
  • python 装饰器

    概述

      了解装饰器之前先了解下什么是闭包,内部函数调用外部变量的行为叫做闭包。装饰器就是闭包的一种,装饰器作用是可以让你代码看上去更简洁。以下详细介绍了闭包代码和装饰器代码(闭包调用函数外部变量延长了外部变量的生命周期而普通函数进入另个一个函数是变量就无法再用。)

    详解

    1)闭包是内部函数调用外部变量

    2)装饰器是闭包的一种

    3)装饰器调用的外部变量是一个函数

    4)装饰器来修饰函数,不用重复修改函数或者增加新的封装。

    5)修饰符提高了程序的可重复利用性,并增加了程序的可读性代码看上去更简洁

    代码

    闭包

    def waiBu(name):
        def neiQian():
            print('my name is ',name)
        #1)调用内部函数
        #2)调用的内部函数是针对waiBu()函数来讲的
        #3)闭包中return内容只能return当前函数内嵌函数,不能return内嵌函数的内嵌函数
        #4)可以return当前函数再被外层函数return
        #5)内嵌的内嵌函数可以使用最外层的函数参数
        return neiQian()
    #针对上面注释3/4/5的代码示例如下:
    #def waiBu(name):
    #    def neiQian():
    #        def neiQian1():
    #           def neiQian2():
    #                print('my name is',name)
    #            return neiQian2()
    #        return neiQian1()
    #    return neiQian()
    
    if __name__=='__main__':
        #输出'my name is tory'
        waiBu('tory')

    装饰器详解1:

    def a_new_decorator(a_func):
     
        def wrapTheFunction():
            print("I am doing some boring work before executing a_func()")
     
            a_func()
     
            print("I am doing some boring work after executing a_func()")
     
        return wrapTheFunction
     
    def a_function_requiring_decoration():
        print("I am the function which needs some decoration to remove my foul smell")
     
    a_function_requiring_decoration()
    #outputs: "I am the function which needs some decoration to remove my foul smell"
     
    a_function_requiring_decoration = a_new_decorator(a_function_requiring_decoration)
    #now a_function_requiring_decoration is wrapped by wrapTheFunction()
     
    a_function_requiring_decoration()
    #outputs:I am doing some boring work before executing a_func()
    #        I am the function which needs some decoration to remove my foul smell
    #        I am doing some boring work after executing a_func()

    装饰器详解2:这里我们可以用@简短方式来生成一个被装饰代码,为了不重写原有代码需要在原有代码加上@wraps(functionName)修饰符

    from functools import wraps
     
    def a_new_decorator(a_func):
        @wraps(a_func)
        def wrapTheFunction():
            print("I am doing some boring work before executing a_func()")
            a_func()
            print("I am doing some boring work after executing a_func()")
        return wrapTheFunction #此处因为函数a_func作为变量,所以不需要retrun wrapTheFunction或a_newdecorator(a_func)()
     
    @a_new_decorator
    def a_function_requiring_decoration():
        """Hey yo! Decorate me!"""
        print("I am the function which needs some decoration to "
              "remove my foul smell")
     
    print(a_function_requiring_decoration.__name__)
    # Output: a_function_requiring_decoration
    from functools import wraps
    def decorator_name(f):
        @wraps(f)
        def decorated(*args, **kwargs):
            if not can_run:
                return "Function will not run"
            return f(*args, **kwargs)
        return decorated
     
    @decorator_name
    def func():
        return("Function is running")
     
    can_run = True
    print(func())
    # Output: Function is running
     
    can_run = False
    print(func())
    # Output: Function will not run

    装饰器的应用场景

    #!/usr/bin/env python
    import logging
    def use_logging(func):
        def wrapper():
            logging.warn("%s is running" % func.__name__)#运行时控制台输出..
            return func()
        return wrapper 
    @use_logging
    def foo():
        print("i am foo")
    foo()

    参考链接

    https://www.runoob.com/w3cnote/python-func-decorators.html

    https://www.cnblogs.com/gdjlc/p/11182441.html

    https://blog.csdn.net/ljt735029684/article/details/80703649

    https://www.cnblogs.com/lincappu/p/8146141.html

    转载引用请标明出处,本博出自喝了少不如不喝的博客https://home.cnblogs.com/u/wangdadada
  • 相关阅读:
    C#深入浅出 修饰符(二)
    HDU 5785 Interesting
    HDU 5783 Divide the Sequence
    HDU 5781 ATM Mechine
    UVA 714 Copying Books
    uva 1471 Defense Lines
    UVA 11134 Fabled Rooks
    UVA 11572 Unique Snowflakes
    UVA 11093 Just Finish it up
    UVA 10954 Add All
  • 原文地址:https://www.cnblogs.com/wangdadada/p/12241573.html
Copyright © 2011-2022 走看看