Python编程:decorator装饰器
2023-09-14 09:07:12 时间
装饰器:
定义:本质是函数,装饰其他函数,为其他函数添加附加功能
原则:
1、不能修改被装饰的函数源代码
2、不能修改被装饰的函数的调用方式
原理:
1.函数即“变量”
2.高阶函数
- a.把函数名当做实参传递给函数
- b.返回一个函数名
3.嵌套函数
总结:
高阶函数 + 嵌套函数 =》 装饰器
import time
def timer(arg): # 可以接收参数
print("arg:", arg)
def outerWrapper(func): # 接收函数参数
def wrapper(*args, **kwargs): # 装饰器
start_time = time.time()
func(*args, **kwargs)
end_time = time.time()
print("run time of func is %s " % (end_time - start_time))
return wrapper
return outerWrapper
@timer("foo") # 等价于: foo = timer(foo)
def foo(): # 无参
time.sleep(3)
print("this is foo")
@timer("foo2")
def foo2(name): # 带参
time.sleep(3)
print("this is foo2,name = ", name)
foo()
foo2("Tom")
"""OUT:
arg: foo
arg: foo2
this is foo
run time of func is 3.00019907951355
this is foo2,name = Tom
run time of func is 3.000049114227295
"""
保持原有属性不变
# -*- coding: utf-8 -*-
# @File : decorator装饰器.py.py
# @Date : 2018-05-30
# @Author : Peng Shiyu
from functools import wraps
# 带参装饰器
def log(text):
print(text)
# 无参的时候只需要以下代码
def outter(func):
print("call outter")
print(func.__name__)
# 把原始函数的__name__等属性复制到 inner() 函数中
@wraps(func)
def inner(*args, **kwargs):
print("call inner")
return func(*args, **kwargs)
return inner
return outter
@log("new function")
def hello():
print("hello world")
hello()
print(hello.__name__)
"""
new function
call outter
hello
call inner
hello world
hello
"""
基于类的装饰器
class Counter:
def __init__(self, func):
self.func = func
self.count = 0
def __call__(self, *args, **kwargs):
self.count += 1
return self.func(*args, **kwargs)
@Counter
def foo():
pass
for i in range(10):
foo()
print(foo.count) # 10
相关文章
- [Python爬虫] Selenium实现自动登录163邮箱和Locating Elements介绍
- 使用python读取word文件里的表格信息
- Python并发编程__多进程
- python操作zip文件
- python-面向对象-04_面向对象封装案例
- Python基础编程
- python中并行遍历:zip和map-转
- 解析Python编程中的包结构
- Python - 函数式编程
- python_网络编程初探(cs架构+TCP协议)
- Open3D 点云投影到球面 (python详细过程版)
- Python:利用python代码编程实现将视频的avi格式转换为MP4格式
- Python:Python语言的简介(语言特点/pyc介绍/Python版本语言兼容问题(python2 VS Python3))、安装、学习路线(数据分析/机器学习/网页爬等编程案例分析)之详细攻略
- 【 华为OD机试 2023】 最大连续文件之和 / 区块链文件转储系统(C++ Java JavaScript Python)
- Python编程:peewee执行多条原生sql语句
- Python编程:itemgetter获取字典元素和groupby分组
- Python编程:利用ImageMagick转换PDF为图片并识别提取图表
- Python编程:trio模块异步/等待本地I/O库
- Python编程:lambda替代品-operator模块
- 2年python自动化编程自学经历,分享一些学习心得和避坑经验
- 面向切面编程AOP——加锁、cache、logging、trace、同步等这些较通用的操作,如果都写一个类,则每个用到这些功能的类使用多继承非常难看,AOP就是解决这个问题的,python AOP就是装饰器
- Python 并行编程
- Python少儿编程入门篇(4)语句和分支结构