• python装饰器


    python装饰器(其实就是函数对象的复杂应用)

    装饰器两大原则

    1.不修改被装饰对象的源代码
    2.不修改被装饰对象的调用方式

    具体应用场景:如果我们已经上线了一个项目,我们需要修改某一个方法,但是我们不想修改方法的使用方法,这个时候可以使用装饰器。因为软件的维护应该遵循开放封闭原则,即软件一旦上线运行后,软件的维护对修改源代码是封闭的,对扩展功能指的是开放的。

    装饰器的几种实现

    1.简单无参实现

    def outter(func):
        def inner():
            '''在此处添加功能'''
            print("hello")
            func()
        return inner
    def zx():
        print("zx")
    zx=outter(zx)
    zx()
    

    hello
    zx

    2.有参装饰器

    def outter(func):
        def inner(*args,**kwargs):
            '''在此处添加功能'''
            print("hello")
            func(*args,**kwargs)
        return inner
    def zx(a,b):
        print(a,b)
    zx=outter(zx)
    zx("zx","wl")
    

    hello
    zx wl

    3.装饰器语法糖

    def outter(func):
        def inner():
            '''在此处添加功能'''
            print("hello")
            func()
        return inner
    def zx():
        print("zx")
    @outter
    def zx():
        print("zx")
    zx()
    

    hello
    zx

    4.连续装饰器

    def outter1(func):
        def inner1():
            '''在此处添加功能'''
            print("---------")
            func()
            print("---------")
        return inner1
    def outter2(func):
        def inner2():
            '''在此处添加功能'''
            print("111111111")
            func()
            print("111111111")
        return inner2
    @outter1
    @outter2# 先运行最下面的装饰器
    def zx():
        print("zx")
    zx()
    

    ---------
    111111111
    zx

    111111111
    ---------

    等价于(看的时候进入函数看方能看懂)

    def zx():
        print("zx")
    zx=outter2(zx)
    zx=outter1(zx)
    zx()
    

    5.三层装饰器(主要针对增加的功能可能需要外接的参数)

    def wai(x):
        def outter(func):
            def inner():
                print("hello")
                func()
                print(x)
            return inner
        return outter
    @wai("world")
    def zx():
        print("zx")
    zx()
    

    hello
    zx
    world

    等价于

    def zx():
        print("zx")
    aa=wai("world")
    zx=aa(zx)
    zx()
    
  • 相关阅读:
    [转]The Regular Expression Object Model
    [转]Blue Prism Interview Questions and Answers
    [转]Date and String Function in BluePrism
    [转]Have a query in Blue prism coding stage and collection stage.
    [转]Blue Prism VBO Cheat Sheet
    [转]秒杀系统优化方案之缓存、队列、锁设计思路
    [转]How to: Create a Report Server Database (Reporting Services Configuration)
    [转]Python in Visual Studio Code
    [转]How to Download and Setup Blue Prism
    [转]Blue Prism Architecture
  • 原文地址:https://www.cnblogs.com/zx125/p/11340411.html
Copyright © 2020-2023  润新知