Article Directory
Discuss decorators again
# 定义函数:完成包裹数据
def makeBold(fn):
def wrapped():
return "<b>" + fn() + "</b>"
return wrapped
# 定义函数:完成包裹数据
def makeItalic(fn):
def wrapped():
return "<i>" + fn() + "</i>"
return wrapped
@makeBold
def test1():
return "hello world-1"
@makeItalic
def test2():
return "hello world-2"
@makeBold
@makeItalic
def test3():
return "hello world-3"
print(test1())
print(test2())
print(test3())
operation result:
hello world-1
hello world-2
hello world-3
4. Decorator function
- import log
- Function execution time statistics
- Preparing before executing the function
- Cleanup function after function execution
- Scenarios such as permission verification
- cache
5. Decorator example
Example 1: Function without parameters
def check_time(action):
def do_action():
action()
return do_action
@check_time
def go_to_bed():
print('去睡觉')
go_to_bed()
The above code understands the execution behavior of the decorator and can be understood as
result = check_time(go_to_bed) # 把go_to_bed 当做参数传入给 check_time函数,再定义一个变量用来保存check_time的运行结果
result() # check_time 函数的返回值result是一个函数, result()再调用这个函数,让它再调用go_to_bed函数
Example 2: The decorated function has parameters
def check_time(action):
def do_action(a,b):
action(a,b)
return do_action
@check_time
def go_to_bed(a,b):
print('{}去{}睡觉'.format(a,b))
go_to_bed("zhangsan","床上")
Example 3: The decorated function has variable length parameters
def test(cal):
def do_cal(*args,**kwargs):
cal(*args,**kwargs)
return do_cal
@test
def demo(*args):
sum = 0
for x in args:
sum +=x
print(sum)
demo(1, 2, 3, 4)
Example 4: return in a decorator
def test(cal):
def do_cal(*args,**kwargs):
return cal(*args,**kwargs) # 需要再这里写return语句,表示调用函数,获取函数的返回值并返回
return do_cal
@test
def demo(a,b):
return a + b
print(demo(1, 2)) #3
Summary:
In general, in order to make the decorator more general, there can be return
Example 5: Decorator with parameters
def outer_check(time):
def check_time(action):
def do_action():
if time < 22:
return action()
else:
return '对不起,您不具有该权限'
return do_action
return check_time
@outer_check(23)
def play_game():
return '玩儿游戏'
print(play_game())
Improve: use decorator to implement permission verification
The following code is not required to be mastered, it is best if you can understand it, if you can write it out manually, that would be great!
def outer_check(base_permission):
def check_permission(action):
def do_action(my_permission):
if my_permission & base_permission:
return action(my_permission)
else:
return '对不起,您不具有该权限'
return do_action
return check_permission
READ_PERMISSION = 1
WRITE_PERMISSION = 2
EXECUTE_PERMISSION = 4
@outer_check(base_permission=READ_PERMISSION)
def read(my_permission):
return '读取数据'
@outer_check(base_permission=WRITE_PERMISSION)
def write(my_permission):
return '写入数据'
@outer_check(base_permission=EXECUTE_PERMISSION)
def execute(my_permission):
return '执行程序'
print(read(5))
Advanced case
[Python] Python realizes the word guessing game-challenge your intelligence and luck!
[python] Python tkinter library implements GUI program for weight unit converter
[python] Use Selenium to get (2023 Blog Star) entries
Use Tencent Cloud Cloud studio to realize scheduling Baidu AI to realize text recognition
[Xiaobai must see] Python word cloud generator detailed analysis and code implementation
[Xiaobai must see] Python crawls an example of NBA player data
[Must-see for Xiaobai] Sample code for crawling and saving Himalayan audio using Python
[Xiaobai must see] Python crawler data processing and visualization
[Must-see for Xiaobai] Python crawler program to easily obtain hero skin pictures of King of Glory
[Must-see for Xiaobai] Use Python to generate a personalized list Word document
Geospatial data processing and visualization using geopandas and shapely (.shp)
Use selenium to crawl Maoyan movie list data
Detailed explanation of the principle and implementation of image enhancement algorithm Retinex
Getting Started Guide to Crawlers (8): Write weather data crawler programs for visual analysis
Getting started with crawlers (4): The best way to crawl dynamic web pages using Selenium and API
Getting Started Guide to Crawlers (3): Python network requests and common anti-crawler strategies
Getting started with crawlers (2): How to use regular expressions for data extraction and processing
Getting started with reptiles (1): Learn the basics and skills of reptiles
Python object-oriented programming basics and sample code
MySQL database operation guide: learn how to use Python to add, delete, modify and query operations
Python file operation guide: encoding, reading, writing and exception handling
Selenium Automation Toolset - Complete Guide and Tutorials
Python web crawler basics advanced to actual combat tutorial
Pandas data processing and analysis tutorial: from basics to actual combat
Detailed explanation of commonly used data types and related operations in Python
[Latest in 2023] Detailed Explanation of Six Major Schemes to Improve Index of Classification Model