Home  >  Article  >  Backend Development  >  What does a python decorator start with?

What does a python decorator start with?

(*-*)浩
(*-*)浩Original
2019-07-20 13:30:523273browse

Decorators are an important part of Python. Simply put: they are functions that modify the functionality of other functions. They help make our code shorter and more Pythonic.

What does a python decorator start with?

#If you want to understand decorators in Python, you must first understand the concept of closure. (Recommended learning: Python video tutorial)

In computer science, closure (English: Closure), also known as lexical closure (Lexical Closure) or function closure ( function closures) are functions that reference free variables. The referenced free variable will remain with the function even after it has left the environment in which it was created.

Decorator

An ordinary decorator generally looks like this:

import functools

def log(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        print('call %s():' % func.__name__)
        print('args = {}'.format(*args))
        return func(*args, **kwargs)

    return wrapper

This defines a decoration that prints out the method name and its parameters. device.

To call it, must start with @:

@logdef test(p):
    print(test.__name__ + " param: " + p)
    
test("I'm a param")

Output:

call test():
args = I'm a param
test param: I'm a param

When the decorator is used, the @ syntax is used, It's a bit troubling. In fact, the decorator is just a method, no different from the following calling method:

def test(p):    print(test.__name__ + " param: " + p)

wrapper = log(test)
wrapper("I'm a param")

@The syntax is just to pass the function into the decorator function, there is nothing magical about it.

It is worth noting @functools.wraps(func), which is the decorator provided by python. It can copy the meta information of the original function to the func function in the decorator. The metainformation of the function includes docstring, name, parameter list, etc.

You can try to remove @functools.wraps(func), you will find that the output of test.__name__ becomes wrapper.

For more Python related technical articles, please visit the Python Tutorial column to learn!

The above is the detailed content of What does a python decorator start with?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:Why use class in pythonNext article:Why use class in python