In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
Python how to understand and use the decorator @ decorator, many novices are not very clear about this, in order to help you solve this problem, the following editor will explain for you in detail, people with this need can come to learn, I hope you can gain something.
Python's decorator is a great mechanism and one of the must-kill skills to skillfully use Python. Decorator, as the name implies, is used for decoration, it decorates a function, keeps the original function of the decorated function, and then decorates (embellishes) some other functions, and returns the function object with new functions, so the decorator is essentially a function that returns the function object (specifically, the decorator should be a callable object, in addition to the function, the class can also be used as a decorator).
In the process of programming, we often encounter such scenarios: login verification, permission verification, logging and so on. These functional codes may be needed in all aspects, but they are very similar. This kind of scenario can be well solved by abstracting and stripping this part of the code through the decorator.
What is the decorator?
To understand Python's decorator, let's first understand Python's function object. We know that in Python, everything is an object, and functions are no exception. Functions are the first kind of objects (first-class objects), which can be assigned to variables, can also be used as elements of list, and can be passed to other functions as parameters.
Functions can be referenced by variables
Define a simple function:
Def say_hi (): print ('hides') say_hi () # Output: Hi!
We can reference the say_hi function through another variable, say_hi2:
Say_hi2 = say_hiprint (say_hi2) # Output: say_hi2 () # Output: Hi!
In the above statement, say_hi2 and say_hi point to the same function definition, and their execution results are the same.
Functions can be passed as arguments to other functions def say_more (say_hi_func): print ('More') say_hi_func () say_more (say_hi) # Output:# More# Hi
In the above example, we pass the say_hi function as an argument to the say_more function, and say_hi is referenced by the variable say_hi_func.
Functions can be defined inside other functions def say_hi (): print ('hides') Def say_name (): print ('Tom') say_name () say_hi () # Output:# hides # Tomsay_name () # error
In the above code, we define another function, say_name (), inside the say_hi () function. Say_name () is visible only inside the say_hi function (that is, its scope is inside the say_hi function), and errors occur when say_hi is outsourced.
Functions can return references to other functions def say_hi (): print ('hides') Def say_name (): print ('Tom') return say_namesay_name_func = say_hi () # print hides, and returns say_name function object # and assigns values to say_name_funcsay_name_func () # print Tom
In the above example, the say_hi function returns a reference to its internally defined function say_name. In this way, the say_name function can also be used outside the say_hi function.
We understood the function earlier, which helps us to understand the decorator next.
Decorator (Decorator)
A decorator is a callable object (callable objects) that modifies a function or class.
A callable object is an object that accepts some parameters and returns some objects. Functions and classes in Python are callable objects.
The function decorator takes the function as a parameter, wraps the function parameters, and then returns the function with the added wrapper, that is, a new function is generated.
Let's look at the following example:
Def decorator_func (some_func): # define another wrapper function which modifies some_func def wrapper_func (): print ("Wrapper function started") some_func () print ("Wrapper function ended") return wrapper_func # Wrapper function add something to the passed function and decorator returns the wrapper function def say_hello (): print ("Hello") say_hello = decorator_func (say_hello) say_hello () # Output:# Wrapper function started# Hello# Wrapper function ended
In the above example, decorator_func is the defined decorator function that accepts some_func as an argument. It defines a wrapper_func function that calls some_func but also adds some of its own code.
The method of using the decorator in the above code looks a bit complicated, but the Python syntax of the real decorator looks like this:
The Python syntax of the decorator @ decorator_funcdef say_hi (): print 'hides'
@ coincidence is the syntax sugar of the decorator, which is used when defining the function say_hi, avoiding the assignment statement again.
The above statement is equivalent to:
Def say_hi (): the order of print 'hippie decorators = decorator_func (say_hi) decorators @ a@b@cdef foo (): print (' foo') # is equivalent to: foo = a (b (c (foo) def decorator_func (some_func): def wrapper_func (* args, * * kwargs): print ("Wrapper function started") some_func (* args) * * kwargs) print ("Wrapper function ended") return wrapper_func@decorator_func def say_hi (name): print ("Hi!" + name)
In the above code, the say_hi function takes an argument. In general, functions with different functions can have different categories and different numbers of parameters. When writing wrapper_func, we are not sure the name and number of parameters. We can refer to function parameters through * args and * * kwargs.
Decorator with parameters
Not only can the decorated function take arguments, but the decorator itself can also take arguments. Refer to the following example:
Def use_logging (level): def decorator (func): def wrapper (* args, * * kwargs): if level= = "warn": logging.warn ("% 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)
To put it simply, a decorator with parameters is a function that nests a parameter outside the decorator without parameters, and the function returns the decorator without parameters.
Class as a decorator
We mentioned earlier that the decorator is a callable object. In Python, in addition to functions, classes are also callable objects. The use of class decorator has the advantages of flexibility, high cohesion and encapsulation. By implementing the _ _ call__ method inside the class, this method is called when the decorator is attached to the function using @ syntax sugar.
Class Foo (object): def _ init__ (self, func): self._func = funcdef _ call__ (self): print ('class decorator runing') self._func () print (' class decorator ending') @ Foodef say_hi (): print ('hides') say_hi () # Output:# class decorator running# hides # class decorator endingfunctools.wraps
Using the decorator greatly reuses the code, but one disadvantage is that the meta-information of the original function is missing, such as docstring, _ _ name__, and parameter list of the function. Let's take a look at the following example:
Def decorator_func (some_func): def wrapper_func (* args, * * kwargs): print ("Wrapper function started") some_func (* args * * kwargs) print ("Wrapper function ended") return wrapper_func@decorator_func def say_hi (name):''Say hi to somebody''' print ("Hi!" + name) print (say_hi.__name__) # Output: wrapper_funcprint (say_hi.__doc__) # Output: None
As you can see, the say_hi function is replaced by the wrapper_func function, and its _ _ name__ and docstring are naturally wrapper_func functions.
But don't worry, Python has functools.wraps,wraps itself is also a decorator, its function is to copy the meta-information of the original function to the decorator function, so that the decorator function has the same meta-information as the original function.
From functools import wrapsdef decorator_func (some_func): @ wraps (func) def wrapper_func (* args, * kwargs): print ("Wrapper function started") some_func (* args * * kwargs) print ("Wrapper function ended") return wrapper_func@decorator_func def say_hi (name):''Say hi to somebody''' print ("Hi!" + name) print (say_hi.__name__) # Output: say_hiprint (say_hi.__doc__) # Output: built-in decorator for the Say hi to somebody class
Class attribute @ property
Static method @ staticmethod
Class method @ classmethod
Typically, we need to instantiate an object of a class before calling its methods.
If the class's method uses @ staticmethod or @ classmethod, you can directly name the class without instantiation. Called by the method name ().
In terms of usage, @ staticmethod does not need to refer to the self of its own object or the cls parameter of its own class, just like using a normal function. The self parameter is not required for @ classmethod, but the first parameter must be the cls parameter that refers to its own class. If you want to call some property methods of this class in @ staticmethod, you can only call the class name directly. Property name, or class name. The way the method name is called.
Since @ classmethod holds the cls parameter, it can call the properties of the class, the methods of the class, the instantiated object, and so on.
Summary
By understanding the function of Python, we gradually understand the context of the decorator. Decorators are good tools for code reuse and can be used in appropriate scenarios in the programming process.
Is it helpful for you to read the above content? If you want to know more about the relevant knowledge or read more related articles, please follow the industry information channel, thank you for your support.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.