zoukankan      html  css  js  c++  java
  • Python学习系列之装饰器

    装饰器的作用

    装饰器用于装饰某个函数、方法或者类,它可以让这个函数执行之前或者执行之后做一些操作

    手工实现一个装饰器

    def outer(some_func):   #装饰器  $1
        def inner():
            print("before some_func")$3
            ret = some_func()        $2
            print('after some_func') $4
        return inner
    
    
    
    def foo():              #被装饰的函数
        print(1)
    decorator = outer(foo)  #把foo函数当做参数传给outer函数 $5
    decorator()             #在执行函数

    让我们一步步来分析

    1.outer函数是装饰器

    2.foo函数是被装饰

    3.$5处把foo函数当做参数传进outer函数

    4.$1处outer函数接收foo函数这个参数

    5.$2处inner函数接收outer函数传进来的参数(此例子为:foo函数),ret用来接收foo函数的结果.(inner函数在本函数内找some_func参数找不到就会向上一级找,就找到了,这是python的作用域(闭包),)

    6.$3处是在foo函数的结果之前加一段代码,$4处是在foo函数的结果之后加一段代码

    所以说原理就是把函数传到装饰器函数里,被装饰函数执行之前先执行一段你想执行的diamante,被装饰函数执行之后再执行一段你想执行的代码

    利用装饰器装饰一个函数

    定义被装饰函数

    代码:
    #!/usr/bin/env python
    # _*_ coding: utf-8 _*_
    def foo(arg):    # 接受一个参数arg
        print(arg)   # 输出这个参数
    foo("Hello World!")  # 调用脚本并且传入参数

    现在要在foo函数执行之前和执行之后来执行一些操作

    #!/usr/bin/env python
    # _*_ coding: utf-8 _*_
    def decorator(func):  # 创建一个装饰器函数,接受的参数arg参数就是func函数名
        def inner(*args, **kwargs):
            print("执行函数之前")
            ret = func(*args, **kwargs)
            print("执行函数之后")
            return ret
        return inner
    @decorator  # 如果要让某个函数使用装饰器,只需要在这个函数上面加上@+装饰器名
    def foo(arg):
        print(arg)
    foo(
    "Hello World!") #执行函数,测试

    测试结果

    执行函数之前
    Hello World!
    执行函数之后

    多个装饰器装饰同一个函数

    #!/usr/bin/env python
    # _*_ coding: utf-8 _*_
    def decorator1(func):
        def inner():
            print("开始之前执行装饰器01")
            ret = func()
            print("结束之后执行装饰器01")
            return ret
        return inner
    def decorator2(func):
        def inner():
            print("decorator2>>>Start...")
            ret = func()
            print("decorator2>>>End...")
            return ret
        return inner
    @decorator1
    @decorator2
    def index():
        print("执行函数...")
    index()#执行函数测试

    结果

    开始之前执行装饰器01
    decorator2>>>Start...
    执行函数...
    decorator2>>>End...
    结束之后执行装饰器01
  • 相关阅读:
    Ubuntu 14.04/16.04/18.04安装最新版Eigen3.3.5
    Ubuntu16.04系统安装谷歌浏览器(Google chorm)
    Anaconda3(6)安装opencv
    Ubuntu 16.04 几个国内更新源
    Anaconda3(4-1)ubuntu1604安装pytorch
    Anaconda3(5-3)ubuntu1604安装pycharm
    无人机姿态定位
    Ubuntu16.04--安装Anaconda
    Airsim(1)安装配置win10-vs2015-cuda10-opencv394+扩展版版本+cmake
    cuda加速拼接
  • 原文地址:https://www.cnblogs.com/chadiandianwenrou/p/6370935.html
Copyright © 2011-2022 走看看