Detailed explanation and examples of decorator

高洛峰
Release: 2017-03-28 16:18:10
Original
1640 people have browsed it

Decorator

1. Definition

1. Decorator: essentially a function

2. Function: used to decorate other functions, Add additional functions to other functions

2. Principles

1. The source code of the decorated function cannot be modified

2. The calling method of the decorated function cannot be modified

3. Implementing decorators

1. Function is the concept of variable

2. Higher-order function

3. Nested function

>> Higher-order function + nested function = decorator

4. Functions are variables

1. Analogy between functions and variables

x = 1
print(id(x))
def test():
	pass
print(test)
#输出
1842348496
<function></function>
Copy after login

In the above example, we defined a variable "x" and a function test(), and we printed out the locations of the variable and function in memory respectively. It can be seen that when print(test) is print("function name"), we can print out the memory address of the function.

Let’s look at the following code:

def test():
	print("in the test.")
f=test
f()
#输出
in the test.
Copy after login

We assign the function name test to f, and then run f(). It can be seen that the function can run normally, and it is the running of the test function result. So is this similar to the following code:

x = 1
y = x
print(y)
#输出
1
Copy after login

We can make the following analogy, the function name test is equivalent to x, the function body is equivalent to 1, and f is equivalent to y.

2.PythonThe representation of memory

  Detailed explanation and examples of decorator

We regard the green square as memory, and each small square is a variable Or the address of the function in memory. As for variable name(x) or function name(test), we can vividly compare them to house numbers. When we need to call a variable or function, we only need to reference their house number to find their memory address and return it. Only () needs to be added to run the function, such as test().

Since calling a variable actually refers to the memory address of the variable, calling the function name can also get the memory address of the function body. We can pass the function name to the function as a variable name, that is, the function is a variable. A function that takes a function as a parameter is a higher-order function.

5. Higher-order functions

Meeting one of the following conditions is a higher-order function

1. Pass a function name as an actual parameter to another function

2. The return value contains the function name

1) The function name is used as a parameter

import time
def test1():
	time.sleep(2)
	print("in the test1.")
def test2(func):
	start_time = time.time()
	func()
	stop_time = time.time()
	print("The action time of program is {}".format(stop_time-start_time))
test2(test1)
#输出
in the test1.
The action time of program is 2.0012054443359375
Copy after login

In the above example, we defined a function test1 and also defined a higher-order function test2 . We pass the test1 function name as a parameter into test2, which can achieve such a function and add a function to calculate the running time to the original test1 function. This is a bit like a decorator, but one thing is consistent, that is, the above high-order function test2 changes the way the function is called.

But we have added new functions without modifying the decorated function.

2) The return value contains the function name

def test1():
	time.sleep(2)
	print("in the test1.")
def test2(func):
	print(func)
	return func
test1 = test2(test1)
test1()
#输出
<function>
in the test1.</function>
Copy after login

In the above example, we finally assigned the high-order function test2 (test1) to test1 and called the test1 function again. We can intuitively see that the calling method of test1 function has not changed in this example. But no new functionality is added, which requires the use of nested functions.

6. Nested function

There is a complete definition of another function in the function body, which is a nested function.

1) Definition:

def foo():
	print("in the foo")
	def bar():
		print("in the bar")
	bar()
foo()
Copy after login

Just calling a function within the function content is not a nested function, as follows:

def test1():
    print("in the test1.")
def test2():
    test1()
Copy after login

2) The scope of the nested function

Access sequence of local scope and global scope

x = 0
def grandpa():
	x = 1
	def dad():
		x = 2
		def son():
			x = 3
			print(x)
		son()
	dad()
grandpa()
#输出
3
Copy after login

3) Use nested functions to add new functions to the modified function

In the second example of a high-order function, we implement It does not change the calling method of the original function. If new functions need to be added, the modified content is required to exist in the return value, that is, in return func. We can define a nested function to implement this function.

import time
def timer(func):  # timer(test1) func = test1
	def deco():
		start_time = time.time()
		func()   # run test1()
		stop_time = time.time()
		print("the action time of the program is {}".format(stop_time-start_time))
	return deco   # 返回了deco的内存地址
def test1():
	time.sleep(2)
	print("in the test1.")
test1 = timer(test1)
test1()
# 输出 
in the test1.
the action time of the program is 2.0003786087036133
Copy after login

We define a nested function deco() inside timer(). This nested function implements the function of adding running time to the modified function. The timer() function returns the memory address of deco(). This memory address deco can be referenced or even assigned directly to test1. In this way we can run test1() directly, thus realizing the function of our decorator.

7. Decorator

Python wraps functions by adding a decorator name and the @ symbol before the function definition

import time
def timer(func):  # timer(test1) func = test1
	def deco():
		start_time = time.time()
		func()   # run test1()
		stop_time = time.time()
		print("the action time of the program is {}".format(stop_time-start_time))
	return deco   # 返回了deco的内存地址
@timer   # test1 = timer(test1)
def test1():
	time.sleep(2)
	print("in the test1.")
test1()
Copy after login

The above is the detailed content of Detailed explanation and examples of decorator. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template