Python decorators in-depth understanding of

1, open closed principle:

(1) an open code extension

Any program, beginning in the design could not have thought of all the features and without any future updates and modifications. So we must allow code extensions, add new features.

(2) modify the source code is closed

When we write a function that has been delivered to others to use, if this time we modify the internal function, or modify the function is called, it is likely to affect other users already using the function.

Without modifying the source code and call mode, the function is to add additional open closed principle

2, decorator:

Without changing the original function is decorative as well as the source code is called, to add additional functionality.

(1) first met decorators:

Decoration (additional features) (Tools: Function)

import time

def index():
    time.sleep(2)  #
    print("这是小明写的功能")

def func():
    time.sleep(1)  #
    print("这是小刚写的功能")

def red():
    time.sleep(2)  #
    print("这是小红写的功能")

start_time = time.time()  # 时间戳
index()
print(time.time() - start_time)

start_time = time.time()  # 时间戳
func()
print(time.time() - start_time)

start_time = time.time()  # 时间戳
red()
print(time.time() - start_time)

(This method returns the GMT, is at this moment the number of seconds from the time at 0:00:00 on January 1, 1970 is also called a time stamp, it has been changed.)

import time
print(time.time())

Repeat the above code, tedious

The seek time is improved :( written in a function, the function is the function-oriented, reduce the duplication of code)

import time

def index():
    time.sleep(2)  #
    print("这是小明写的功能")

def func():
    time.sleep(1)  #
    print("这是小刚写的功能")

def red():
    time.sleep(2)  #
    print("这是小红写的功能")

def times(func):
    start_time = time.time()  # 时间戳
    func()
    print(time.time() - start_time)

times(index)
times(func)

Improve:

第一版装饰器
import time
def func():
    time.sleep(1)  #
    print("这是小刚写的功能")

def red():
    time.sleep(2)  #
    print("这是小红写的功能")

def index():
    time.sleep(2)  #
    print("这是小明写的功能")

def times(func):
    def foo():
        start_time = time.time()  # 时间戳  被装饰函数执行前干的事
        func()
        print(time.time() - start_time) #   被装饰函数执行后干的事
    return foo           # 不能加括号

index = times(index)       # 不能加括号
index()
func = times(func)
func()

(2) syntactic sugar (to help us do a thing)

To syntactic sugar written on top of the decorative function
def warpper(f):
    def inner():
        print("111")
        f()
        print("222")
    return inner

# python帮咱们做的一个东西,语法糖
@warpper  # func = warpper(func)
def func():
    print("被装饰的函数1")

@warpper  # index = warpper(index)
def index():
    print("被装饰的函数2")

func()
def warpper(f):
    def inner(*args,**kwargs):
        print("被装饰函数执行前")
        ret = f(*args,**kwargs)
        print("被装饰函数执行后")
        return ret
    return inner

@warpper
def func(*args,**kwargs):
    print(f"被装饰的{args,kwargs}")
    return "我是func函数"

@warpper
def index(*args,**kwargs):
    print(11111)

print(func(1,2,3,4,5,6,7,8,a=1))

(3) Standard Edition decorators:

def wrapper(func):
    def inner(*args,**kwargs):
        '''执行被装饰函数之前的操作'''
        ret = func()
        '''执行被装饰函数之后的操作'''
        return ret
    return inner

This is the standard decorators, in full compliance with the code open closed principle.

4, decorator Advanced

(1) Reference decorator

def auth(argv):
    def warpper(func):
        def inner(*args,**kwargs):
            if argv == "博客园":
                print("欢迎登录博客园")
                user = input("user:")
                pwd = input("pwd:")
                if user == 'alex' and pwd == "dsb":
                    func(*args,**kwargs)
            elif argv == "码云":
                print("欢迎登录码云")
                user = input("user:")
                pwd = input("pwd:")
                if user == 'alex' and pwd == "jsdsb":
                    func(*args, **kwargs)

        return inner
    return warpper

def foo():
    print("被装饰的函数")

msg = input("请输入您要登录的名字:")
a = auth(msg)
foo = a(foo)
foo()
def auth(argv):
    def wrapper(func):
        def inner(*args,**kwargs):
            if argv:
                print("我加上功能了!")
                func(*args,**kwargs)
            else:
                func(*args,**kwargs)
        return inner
    return wrapper

https://www.cnblogs.com/

@auth(True)   # @auth == foo = wrapper(foo) = auth(True)   flask框架
def foo():
    print("这是一个点燃")
foo()

(2) a plurality of decorative function decorator

A plurality of decorator decorative function, perform the function to be decorated from the nearest decorator

def auth(func):             # wrapper1装饰器里的 inner
    def inner(*args,**kwargs):
        print("额外增加了一道 锅包肉")
        func(*args,**kwargs)
        print("锅包肉 38元")
    return inner

def wrapper1(func):        # warpper2装饰器里的 inner
    def inner(*args,**kwargs):
        print("额外增加了一道 刺生")
        func(*args,**kwargs)
        print("刺生 白吃")
    return inner

def wrapper2(func):         # 被装饰的函数foo
    def inner(*args,**kwargs):
        print("额外增加了一道 麻辣哥")
        func(*args,**kwargs)
        print("难以下嘴")
    return inner
    
def foo(): 
    print("这是一个元宝虾饭店")
    
foo = wrapper2(foo) # inner = wrapper2(foo)
foo = wrapper1(foo) # inner = wrapper1(inner)
foo = auth(foo)     # inner = auth(inner)
foo()               # auth里边的inner()
def auth(func):            # wrapper1装饰器里的 inner
    def inner(*args,**kwargs):
        print(123)
        func(*args,**kwargs)
        print(321)
    return inner


def wrapper1(func):         # warpper2装饰器里的 inner
    def inner(*args,**kwargs):
        print(111)
        func(*args,**kwargs)
    return inner


def wrapper2(func):          # 被装饰的函数foo
    def inner(*args,**kwargs):
        print(222)
        func(*args,**kwargs)
        print(567)
    return inner


@auth                 # 1           7
@wrapper1             #   2       6
@wrapper2             #    3    5
def foo():            #      4
    print("www.baidu.com")
foo()

Guess you like

Origin www.linuxidc.com/Linux/2019-09/160551.htm