Dhutsj has worked for EMC and Microsoft. He specializes in Python crawlers, PyTest testing frameworks, and data visualization Elastic Stack.
1. Write at the front
Before I introduce Python decorators, I’ll first introduce one of Python’s concepts, objects. In Python, everything is an object. Common Python objects are integer objects, floating point objects, string objects, list objects, tuples, dictionaries, and so on. One of the more special objects is the function object.
num1 = 1# defines an integer object. Num1 refers to str1 ="aaa"List1 = [list1 = [list1 = [list1 = [list1 = [list1 = [1.2.3Def my_func() def my_func() def my_func() def my_func() def my_func(print "hello world"Func1 = my_func # func1 references this function objectCopy the code
Take an ordinary function.
def my_func(name):
return "name is {}".format(name)
Copy the code
Here we define a function called my_func, pass in a string object as an argument to the function, and return another string object. As mentioned above, in Python, everything is an object. What if we pass in a function object as an argument and then return another function? So that’s the decorator.
2. Base decorators
Following the above question, let’s write a function that looks like this.
Def add(a, b): # defines a function objectreturnA + b myadd = add # myadd references this function object def decorator1(func): # defines a function objectdecorator1, the required argument is also a function objectDef log(*args, **kwargs): # define a new function object log inside the functionreturn func(*args, **kwargs)
returnCall decorator1, pass myadd as an argument, and assign the returned object to mydecorator. That is, mydecorator points to the log functionprint mydecorator(1.2Mydecorator = mydecorator = mydecorator = mydecorator = mydecorator = mydecoratorCopy the code
Take a look at the result of this code execution
C:\Python>python mydecorator1.py
3
Copy the code
We can see that the result of this is 3, and you might say, well, isn’t that just the sum of two numbers? Isn’t that the add function above? The above code is just so you can understand, what if we add some operations to the internal log function? Like printing a log.
def add(a, b):
return a + b
myadd = add
def minus(a, b):
return a - b
myminus = minus
def decorator1(func) :
def log(*args, **kwargs):
# do some things here, for example, add some log
print "function {} was called".format(func.__name__)
return func(*args, **kwargs)
return log
mydecorator1 = decorator1(myadd)
mydecorator2 = decorator1(myminus)
print mydecorator1(1.2)
print mydecorator2(3.4)
Copy the code
Take a look at the result of this code
C:\Python>python mydecorator1.py
function add was called
3
function minus was called
- 1
Copy the code
We only need to modify the internal log function in one place to implement the function extension function, and this function can be applied to multiple functions. That’s what decorators are all about. Here I use logging as an example, in real work, such as writing a decorator to determine whether a login operation is required.
3. Python decorator syntax sugar
In the real world of Python, decorators are often invoked using the @ symbol, called Python syntax sugar.
def decorator1(func) :
def log(*args, **kwargs):
# do some things here, for example, add some log
print "function {} was called".format(func.__name__)
return func(*args, **kwargs)
returnLog @decorator1 def add(a, b)returnA + b@decorator1 def minus(a, b)return a - b
print add(1.2Execute the decorated add function instead of the original add functionprint minus(3.4# Execute the decorated minus function instead of the original minus functionCopy the code
4. Decorator advanced
The basic decorators were introduced above, and some more advanced uses of decorators are described below.
4.1 Decorators with parameters
In the example above, we can see that the decorated functions add and minus take arguments, but decorator1 itself cannot take arguments other than func. Is there a way to make decorators take other parameters? Like string arguments and so on. The answer is yes, just wrap another function in the outermost layer.
def decorator2(mystring):
print mystring
def decorator1(func) :
def log(*args, **kwargs):
# do some things here, for example, add some log
print "function {} was called".format(func.__name__)
return func(*args, **kwargs)
return log
return decorator1
@decorator2("Used decorator here")
def add(a, b):
return a + b
@decorator2("Used decorator here")
def minus(a, b):
return a - b
print add(1.2)
print minus(3.4)
Copy the code
Let’s look at the result of this code
C:\Python>python mydecorator1.py
Used decorator here
Used decorator here
function add was called
3
function minus was called
- 1
Copy the code
4.2 Multiple Decorations
So far, we’ve only used one decorator. What happens if you use multiple decorators?
from functools import wraps
def decorator1(func) :
@wraps(func)
def log(*args, **kwargs):
# do some things here, for example, add some log
print "function {} was called in decorator1".format(func.__name__)
return func(*args, **kwargs)
return log
def decorator2(func) :
@wraps(func)
def another_log(*args, **kwargs):
# do some things here, for example, add some log
print "function {} was called in decorator2".format(func.__name__)
return func(*args, **kwargs)
return another_log
@decorator1
@decorator2
def add(a, b):
return a + b
add(1.2)
@decorator2
@decorator1
def minus(a, b):
return a - b
minus(3.4)
Copy the code
Let’s look at the result of this code
C:\Python>python mydecorator1.py
function add was called in decorator1
function add was called in decorator2
function minus was called in decorator2
function minus was called in decorator1
Copy the code
5. Decoration summary
- A decorator is a function that receives a function object and returns a new function object.
- Decorators can extend code functionality without modifying the decorator function, without rewriting or refactoring code.
- Decorators can often be used to add extended logs to determine whether a user’s operation requires a login, whether it is legal, etc.
- The decorator itself can also take additional parameters as needed.
- For multiple decorations, the order of decoration is the order in which the decorators are invoked.
Recommended reading:
Using Python to implement particle swarm optimization \
Python scheduler: APScheduler\
The 2020 Python job promotion channel is now open! \
Appreciate the author
Python Chinese community as a decentralized global technology community, to become the world’s 210000 Python tribe as the vision, the spirit of Chinese developers currently covered each big mainstream media and collaboration platform, and ali, tencent, baidu, Microsoft, amazon and open China, CSDN industry well-known companies and established wide-ranging connection of the technical community, Have come from more than 10 countries and regions tens of thousands of registered members, members from the ministry, tsinghua university, Peking University, Beijing university of posts and telecommunications, the People’s Bank of China, the Chinese Academy of Sciences, cicc, huawei, BAT, such as Google, Microsoft, government departments, scientific research institutions, financial institutions, and well-known companies at home and abroad, nearly 200000 developers to focus on the platform.
\
▼ clickBecome a registered member of the community if you likeIn the see