当前位置:
首页 > 编程开发 > Python基础教程 >
-
python基础教程之python装饰器原理和用法总结
本站最新发布 Python从入门到精通|Python基础教程
试听地址 https://www.xin3721.com/eschool/pythonxin3721/
试听地址 https://www.xin3721.com/eschool/pythonxin3721/
原理
装饰器本质也是一个函数, 只不过这个函数需要遵循以下规则:
- 入参只能有一个,类型为函数。 被装饰的函数将入会被传入这个参数
- 返回值是必须是一个函数, 届时被调用的时候实际上调用的是返回出来的这个函数,所以返回的函数入参通常是
(*args, **kwargs):
以满足所有函数需要
之后通过@语法糖即可装饰到任意函数上
简单装饰器例子
# 不带参数的装饰器
def pre_do_sth(func):
def wrapper(*args, **kwargs):
print("Do sth before call one")
func(*args, **kwargs)
return wrapper
@pre_do_sth
def echo(msg):
print(msg)
echo("Hello World")
运行结果
Do sth before call one
Hello World
实际上调用的是 wrapper("Hello World") --> echo("Hello World")
带参数的装饰器例子(参数控制的是装饰器的行为)
只需要写一个返回 装饰器(入参只有一个, 返回值是一个函数)函数的函数
同样也能利用@语法糖
# 带参数的装饰器
def pre_do_sth_2(msg):
def decorator(func):
def wrapper(*args, **kwargs):
print("Do sth before call two, print:%s"%(msg))
func(*args, **kwargs)
return wrapper
return decorator
@pre_do_sth_2("Foo")
def echo(msg):
print(msg)
echo("Hello World")
实际上@后面并不是对pre_do_sth_2这个函数生效 而是对pre_do_sth_2的返回值生效
运行结果
Do sth before call two, print:Foo
Hello World
多个装饰器调用顺序
先声明的装饰器先执行, 即在最外层
# 不带参数的装饰器
def pre_do_sth(func):
def wrapper(*args, **kwargs):
print("Do sth before call one")
func(*args, **kwargs)
return wrapper
# 带参数的装饰器
def pre_do_sth_2(msg):
def decorator(func):
def wrapper(*args, **kwargs):
print("Do sth before call two, print:%s"%(msg))
func(*args, **kwargs)
return wrapper
return decorator
@pre_do_sth
@pre_do_sth_2("Foo")
def echo(msg):
print(msg)
echo("Hello World")
运行结果
Do sth before call one
Do sth before call two, print:Foo
Hello World
栏目列表
最新更新
如何使用OS模块中的stat方法
Python os 模块
seek() 方法
python打开文件实例1
Python写入文件
什么是流?
文件操作如何进制逐行读取
Python相对路径
with创建临时运行环境
Python文件操作
.Net Standard(.Net Core)实现获取配置信息
Linux PXE + Kickstart 自动装机
Shell 编程 基础
Shell 编程 条件语句
CentOS8-网卡配置及详解
Linux中LVM逻辑卷管理
1.数码相框-相框框架分析(1)
Ubuntu armhf 版本国内源
Linux中raid磁盘阵列
搭建简易网站
access教程之Access简介
mysql 安装了最新版本8.x版本后的报错:
Mysql空间数据&空间索引(spatial)
如何远程连接SQL Server数据库的图文教程
复制SqlServer数据库的方法
搜索sql语句
sql中返回参数的值
sql中生成查询的模糊匹配字符串
数据定义功能
数据操作功能