Analysis of those things about decorators

Click on " IT Sharing House " above to follow

Reply " information " to receive Python learning benefits

now

day

Chickens

soup

In the end, it is Sheng Ming's affairs, who is Jingyang Gongjing.

1. Simple definition of decorator

The outer function returns a reference to the inner function, and the inner function references the variables of the outer function.

Second, the role of decorators

Generally speaking, the role of the decorator is to add new functions to the function without changing the existing function code.

def run():
   print('我会跑')
fun()

Now I want to add a new function to the original function: I can sing. At this time, using decorators can easily help us achieve this function.

Three, example understanding

(1) Decorator without passing parameters

def outer(fun):
   def inner():
      fun()  //fun是外层函数的变量,在inner里面用
   return inner //inner就是里层函数的引用

(2) Decorator for passing parameters:

def func(fun):
   def add(*args,**kwarge):
      return fun(*args,**kwargs)
   return add

Now that you have a certain understanding of the basic format of decorators, you can write functions directly. Achieved at the beginning of the article below I will sing functions

def outer(fun):
    def inner(*args, **kwarge):
        print("我会唱歌")
        return fun(*args, **kwarge)
    return inner

Fourth, how to use decorators

方法一:使用@符号+装饰器的名字   把它放在想要装饰函数的上一行即可
@outer
def run():
   print('我会跑')
   
run()




方法二:
def run():
    print('我会跑')


run=outer(run)   #就等价于@outer
run()


最终打印结果是:
我会唱歌
我会跑

If I want to know what the parameters passed by fun are, I can use the following methods inside the decorator:

def outer(fun):
    a = 1
    def inner(*args, **kwarge): # args是一个数组,kwargs一个字典
        print(fun.__name__) #打印fun接收的函数的名字
        print("我会唱歌")
        return fun(*args, **kwarge)
    return inner

But if we print(run.__name__,6666666)resulting output is inner, not what we want to run, where the function is warpTheFunction replaced. It rewrites the name and docstring of our function. The solution is as follows:

from functools import wraps


def outer(fun):
    @wraps(fun)
    def inner(*args, **kwargs):
        print(fun.__name__,11111111111)
        print("我会唱歌")
        return fun(*args, **kwargs)
    return inner


@outer
def run():
   print('我会跑')
   
 print(run.__name__,6666666)  //输出结果为 run 666666

 

Five, implement the decorator yourself

def subuser_keymanage(view_func):
    '''功能是实现用户管理权限的判定'''
    def _wrapper_view(request, *args, **kwargs):
        user = request.user #一个Customer对象,包含了用户名/密码等信息
        customer = user.customer.customer_id #用户的id
        select_status = get_curuser_permission(user=user, customer=customer)#调用函数返回的值有两种0和1
        if not select_status:#如果返回0表示没有权限,返回错误码
            return render_response(request, ErrorCode.FAILED)
        return view_func(request, *args, **kwargs)
    return _wrapper_view
@subuser_keymanage 
def generate_subuser_ak_sk(request):
    params = json.loads(request.body) #获取卡前端传递的参数
    user_id_only = params.get("user_id") #获取用户表示id值
    中间代码就忽略了......
    return render_response(request, ErrorCode.FAILED)

Six, decorator summary

Decorators can greatly reduce code reuse, which is very important in code specifications.

The above is the basic knowledge of decorators. Even if you don't have any foundation, follow the author's ideas and apply a fixed format. You don't need to fully understand it. Just follow the process step by step and you can write a high-end and elegant decorator. Congratulations!

Please pay attention to the high energy in the front: the decorator transfers parameters, the three-level nested function is generally used less, in fact, it is not difficult, looking at it layer by layer, just like the above, just as a broadening of knowledge.

import logging
def use_logging(level):
    def decorator(func):
        def wrapper(*args, **kwargs):
            if level == "warn":
                logging.warn("%s is running" % func.__name__)
            elif level == "info":
                logging.info("%s is running" % func.__name__)
            return func(*args)
        return wrapper


    return decorator


@use_logging(level="warn")
def foo(name='foo'):
    print("i am %s" % name)


foo()
i am foo
WARNING:root:foo is running

If you have any problems during the operation, remember to leave a message below, we will see that the problem will be solved as soon as possible.

Have you learned after reading this article? Please forward and share to more people

IT shared home

To join the group, please reply in the WeChat background [Enter the group]

------------------- End -------------------

Recommendations of previous wonderful articles:

Guess you like

Origin blog.csdn.net/pdcfighting/article/details/113622787