Briefly describe the usage of the decorator in Python and briefly describe python
The decorator is a hard-to-understand and hard-to-write tool for anyone new to Python who is so familiar with Python. Today I will share my understanding of the Python decorator.
The so-called decorator is just a syntactic sugar. The objects that can be used can be functions or classes. The decorator itself is a function, the main way to work is to pass the decorated class or function as a parameter to the decorator function, for example, define the following decorator
import timedef run_time(func): def wrapper(*args, **kwargs): start = time.time() r = func(*args, **kwargs) print time.time() - start return r return wrapper
We use this decorator to decorate a test function.
@run_timedef test(): print "just a test"
As mentioned above, the decorator is actually a syntactic sugar, that is, passing the decorated function as a parameter to the decorator function, so the above can be expanded
test = run_time(test)
The decorator will be loaded from the beginning when the interpreter runs, so that the decorated function will be expanded as shown above, because the run_time decorator returns the wrapper function, so when you call the test function, it is actually a wrapper call.
If you execute the preceding statement in Python shell, you will find that when you define the test function and view the test function, shell displays the wrapper function.
Next, let's talk about how to compile a decoration device with parameters. If you are careful, you can find that the decoration device with parameters is a decoration device returned by calling the "decoration" function, the quotation marks on the decorator indicate that the so-called "decorator" is only a common function, but this common function returns a decorator. See the following example:
import timedef route(url): def decorator(func): func.__url__ = url return func return decorator@route(r"/")def index(): return "Hi"
You can find that when using the route decorator, we actually call the route function. The route function returns a decorator, because we do not need to run the function in the decorator, therefore, a wrapper function is not required to collect parameters.
The above is all content. I hope some help will be given to anyone who knows about the decorator.