• python3 装饰器


    python3 装饰器

    一、闭包

    闭包的两个条件:函数内套有内层函数;内层函数引用外层函数定义的变量。

    eg:

    def outer():

        x=10

        def inner():

        print(x)

        return inner

    二、装饰器

    装饰器是为了在不改变原先函数源码的前提下,增加功能而存在的。执行流程:在调用被装饰器修饰的函数时,装饰器会先被调用,将被装饰函数的函数名传入装饰器函数,执行装饰器内层函数,内层函数会调用被装饰函数,从而实现被装饰函数的执行,而增加的功能在内层函数里写着,所以增加的功能也实现了。这样做的好处是,被装饰的函数的调用方法不变,从而防止牵一发而动全身的现象出现;没有改变被装饰函数的源码,符合开放封闭原则。

    注意,装饰器函数必须是闭包函数。

    eg:

    装饰器函数:

    import time
    def show_time(f):
        def inner(*args,**kwargs):      #设定不定长参数,防止被装饰函数有参数
            start_time=time.time()
            f(*args,**kwargs)
            time.sleep(3)
            end_time=time.time()
            print('spend_time=%s'%(end_time-start_time))
        return inner()

     

    @show_time
    def foo():           #被装饰器修饰的函数
        print('ok')

    foo()#调用函数

    如果需要向装饰器函数中传参则在装饰器函数外围在套一层外部函数。

    eg2:

    def outer(*args):

        def show_time(f):

              def inner(*args,**kwargs):

                   pass

             return inner

    return show_time

    @outer(‘参数’)

    def foo ():

        pass

    foo()#调用函数

  • 相关阅读:
    iOS开发Xcode7真机调试教程
    tableView 局部刷新
    CocoaPods 安装
    Mac OS
    iOS
    NSFileManager
    Label Font 字体样式设置
    iOS项目之企业证书打包和发布
    React Native学习之自定义Navigator
    React Native学习之DeviceEventEmitter传值
  • 原文地址:https://www.cnblogs.com/xshan/p/8467515.html
Copyright © 2020-2023  润新知