Home Backend Development Python Tutorial Detailed explanation and examples of decorator

Detailed explanation and examples of decorator

Mar 28, 2017 pm 04:18 PM

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1657
14
PHP Tutorial
1257
29
C# Tutorial
1229
24
Python vs. C  : Applications and Use Cases Compared Python vs. C : Applications and Use Cases Compared Apr 12, 2025 am 12:01 AM

Python is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.

Python: Games, GUIs, and More Python: Games, GUIs, and More Apr 13, 2025 am 12:14 AM

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

How Much Python Can You Learn in 2 Hours? How Much Python Can You Learn in 2 Hours? Apr 09, 2025 pm 04:33 PM

You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

The 2-Hour Python Plan: A Realistic Approach The 2-Hour Python Plan: A Realistic Approach Apr 11, 2025 am 12:04 AM

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Python vs. C  : Learning Curves and Ease of Use Python vs. C : Learning Curves and Ease of Use Apr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

Python and Time: Making the Most of Your Study Time Python and Time: Making the Most of Your Study Time Apr 14, 2025 am 12:02 AM

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Python: Exploring Its Primary Applications Python: Exploring Its Primary Applications Apr 10, 2025 am 09:41 AM

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

Python: Automation, Scripting, and Task Management Python: Automation, Scripting, and Task Management Apr 16, 2025 am 12:14 AM

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

See all articles