current position:Home>The principle of python decorator

The principle of python decorator

2022-08-06 06:13:25Jing Shenhuo

目录

装饰器

在pythonThere are many decorators,So how do we implement the function of the decorator ourselves?

 闭包的条件(缺一不可)

The principles of variable parsing LEGB

什么是pythonDecorator and what it does?


装饰器

在pythonThere are many decorators,So how do we implement the function of the decorator ourselves?

首先要了解一些概念:如生命周期,闭包

生命周期

A module has the life cycle of the module;A class has a class lifecycle;A variable has the lifetime of the variable

闭包

 闭包的条件(缺一不可)

1. 必须有一个内嵌函数 >= 1
2. 内函数必须引用外函数的变量
3. 外函数必须返回内函数

形成闭包之后,闭包函数会得到一个非空的 __closure__属性

# 闭包
# The principles of variable parsing LEGB
def outer(x):
    a = 300
    def inner():
        print(f"两数之和为: {x + a}")
    return inner
d = outer(10)
d()
print(d.__closure__)
​
---- result
两数之和为: 310
(<cell at 0x000001F8763B9A98: int object at 0x000001F876A9D2B0>, <cell at 0x000001F876899948: int object at 0x00007FFB30CC7D60>)

The principles of variable parsing LEGB

L —— Local(function);函数内的名字空间
E —— Enclosing function locals;外部嵌套函数的名字空间(例如closure)
G —— Global(module);函数定义所在模块(文件)的名字空间
B —— Builtin(Python);Python内置模块的名字空间

Now you know what a closure is,就来看看python装饰器

什么是pythonDecorator and what it does?

Decorators must be decorated 具有 __callable __对象

装饰器是这样一种设计模式:如果一个类(函数)Hope to add other classes(函数)的一些功能,Don't want to implement through inheritance or directly modify the source code,那么可以使用装饰器模式
​
通俗的来说:Without changing the source code of the function or class,添加额外功能
装饰器的本质就是闭包函数,The difference is that one needs to be passed in  callable 对象

# 统计运行时间的装饰器
import time
def runtime(func):
    def inner():
        start = time.time()
        func()
        end = time.time()
        print(f"函数执行花了{end - start}s")
    return inner
​
@runtime    # @装饰符 to use the decorator
def func1():
    time.sleep(2)
    print("func1 .....")
​
func1()
​
----result
func1 .....
函数执行花了2.0011112689971924s

优化后的代码(保证代码的健壮性)

# 统计运行时间的装饰器
import time
def runtime(func):
    print("this is runtime")
    def inner(*args,**kwargs): # 让装饰器更加通用
        start = time.time()
        result = func(*args,**kwargs)
        end = time.time()
        print(f"函数执行花了{end - start}s")
        return result
    return inner

@runtime   # func3 = runtime(func3)
def func3(a,b):
    time.sleep(3)

    print(f"func1 {a} + {b} = {a + b}")
    return a + b
func3(2, 6)
result = func3(1, 3)
print(result)
-------------------------result
func1 2 + 6 = 8
函数执行花了3.0104315280914307s
    

copyright notice
author[Jing Shenhuo],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/218/202208060518384785.html

Random recommended