Study Notes (05): Python Interview 100 talking about (based Python3.x) - decorator role

Learning immediately: https://edu.csdn.net/course/play/26755/340161?utm_source=blogtoedu

1. The role of the decorator

Decorator itself is a function, that is, decorator function.

Decorators may, subject to no code changes, add additional functionality to a function, play a decorative role

Demand scenarios such as: insert log, performance testing, transaction processing, caching.

 

Decorator is a common function.

2. Custom Decorators

 

from functools import wraps
def log(flag):
    def decorate(func):
        @wraps(func)
        def _wrap(*args,**kwargs):
            try:
                if flag:
                    func(*args,**kwargs)
                print('name',func.__name__)
            except Exception as e:
                print(e.args)
        return _wrap
    return decorate

@log(False)
def add(a,b,c):
    print('sum','=',a + b + c)

add(1,2,3)

 

 

 

 

 

 

Released seven original articles · won praise 1 · views 100

Guess you like

Origin blog.csdn.net/qq_44980274/article/details/104391568