python装饰器学习案例

该案例是介绍装饰器不含参和含参的区别和使用方式:

不改变原来核心业务逻辑的基础上(如充电、自我介绍),新增外加功能(计时),

装饰器的应用场景:

日志记录: 装饰器可用于记录函数的调用信息、参数和返回值。

性能分析: 可以使用装饰器来测量函数的执行时间。

权限控制: 装饰器可用于限制对某些函数的访问权限。

缓存: 装饰器可用于实现函数结果的缓存,以提高性能。

复制代码
#写一个充电的功能
import time
#定义一个装饰器:无参,用于统计计算一个程序执行的时长
def count_time(func):
    def wrapper(*args,**kwargs):
        start_time = time.time()
        response = func(*args,**kwargs)
        end_time = time.time()
        use_time = int(end_time-start_time)
        print(f"\n耗时{use_time}秒")
        return response
    return wrapper

#定义一个传参的装饰器,执行者是谁
def outer(name):
    def inner(func):
        def wrapper(*args,**kwargs):
            start_time = time.time()
            response = func(*args,**kwargs)
            end_time = time.time()
            use_time = int(end_time-start_time)
            print(f"\n耗时{use_time}秒,属于{name}操作")
            return response
        return wrapper
    return inner

@count_time
def charge(num):
    for i in range(num,101):
        time.sleep(0.05)
        print(f"\r充电中{'▋'*i}{i}%",end="")
@count_time
def introduce(name,age,job):
    time.sleep(2)
    print(f"大家好,我的名字叫{name},我今年{age}岁了,我的是从事{job}工作,很高兴认识大家,谢谢!")
    time.sleep(2)


@outer("李四")
def introduce1(name,age,job):
    time.sleep(2)
    print(f"大家好,我的名字叫{name},我今年{age}岁了,我的是从事{job}工作,很高兴认识大家,谢谢!")
    time.sleep(2)

@outer(name="张三")
def charge1(num):
    for i in range(num,101):
        time.sleep(0.05)
        print(f"\r充个电中{'▋'*i}{i}%",end="")

charge(40)
introduce("张三",22,"python开发工程师")
charge1(20)
introduce1("李四",24,"python开发工程师")
相关推荐
yuanpan8 分钟前
.net/C#进程间通信技术方案总结
开发语言·c#·.net
烟雨迷14 分钟前
Linux环境基础开发工具的使用(yum、vim、gcc、g++、gdb、make/Makefile)
linux·服务器·学习·编辑器·vim
吃面不喝汤6616 分钟前
破解 Qt QProcess 在 Release 模式下的“卡死”之谜
开发语言·qt
@十八子德月生24 分钟前
8天Python从入门到精通【itheima】-1~5
大数据·开发语言·python·学习
jiunian_cn24 分钟前
【c++】异常详解
java·开发语言·数据结构·c++·算法·visual studio
martian66536 分钟前
信创生态核心技术栈:数据库与中间件
开发语言·中间件·系统架构·系统安全·创业创新
Bl_a_ck1 小时前
开发环境(Development Environment)
开发语言·前端·javascript·typescript·ecmascript
每天一个秃顶小技巧1 小时前
02.Golang 切片(slice)源码分析(一、定义与基础操作实现)
开发语言·后端·python·golang
Clockwiseee2 小时前
文件上传总结
运维·服务器·学习·文件上传
苜柠2 小时前
Wpf学习片段
学习