Decorators and namespaces

Decorator:

We can directly modify our previous similar function codes to complete the new functions we need, but some problems will arise:
1. If there are many modifications, it will be more troublesome to modify
2. Not conducive to subsequent maintenance
3. Violation The open and close principle of writing code (OCP, O:open, C:close, P:principle)
is that when the program is expanded, the program cannot be modified (without changing the source code, the program is functionally Add)
Through the decorator , you can introduce new functions without changing the source code

def s(a,b):
    print(a,'+',b,'=',a+b)
# s(10,20)
def m(a,b):
    print(a,'*',b,'=',a*b)
# m(11,22)
def new(n,a,b):
    print('开始计算')
    r = n(a,b)
    print('计算结束')
    return r
p = new(m,11,22)

We can see that the custom functions s and m calculate the addition and subtraction of two numbers respectively. By customizing a new function, we can print the start and end of the calculation when calling these two functions.

def s(a,b):
    print(a,'+',b,'=',a+b)
# s(10,20)
def m(a,b):
    print(a,'*',b,'=',a*b)
# m(11,22)
#fun:调用的或者旧的函数
def a(fun):
    def e(a,b):
        print("计算开始")
        r = fun(a,b)
        print("计算结束")
        return r
    return e
z = a(m)
s = z(1,2)

When we set the function, we can set the formal parameters to *a,**b, which is convenient for receiving various actual parameters.
In development, the expansion of the program is carried out through the decorator

Namespaces

Namespace: A dictionary specially used to save variables.
Use locals() to get the namespace of the current function scope. There is a return value. When returning a dictionary,
Insert picture description hereyou can use locals() to add key-value pairs to the namespace, which is equivalent to global Created a variable

Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_51864831/article/details/109845794