首页 > 编程语言 >Python之装饰器

Python之装饰器

时间:2023-01-29 00:55:43浏览次数:37  
标签:return Python inner func time print 装饰 def

# 装饰器功能说明
"""
    python中的装饰器(decorator)一般采用语法糖的形式,是一种语法格式。
        比如:@classmethod,@staticmethod,@property,@xxx.setter,@wraps(),@func_name等都是python中的装饰器。
    装饰器,装饰的对象是函数或者方法。各种装饰器的作用都是一样的:改变被装饰函数或者方法的功能,性质。
"""
import time


def how_much_time(func):
    print("how_much_time函数开始运行")

    def inner():
        t_start = time.time()
        func()
        t_end = time.time()
        print(f"一共花费了{t_end - t_start:.6f}秒时间")

    return inner


# @how_much_time等价于sleep_1s = how_much_time(sleep_1s)
@how_much_time
def sleep_1s():
    """
    how_much_time函数开始运行
    1秒结束了
    一共花费了1.007465秒时间
    """
    time.sleep(1)
    print("%d秒结束了" % (1,))


sleep_1s()  # 执行


def mylog(func):
    print("mylog函数开始运行")

    def inner_2():
        print("start")
        func()
        print("end")

    return inner_2


# 多个装饰器demo1,等价于mylog(how_much_time(sleep_more))
@mylog
@how_much_time
def sleep_more():
    """
    how_much_time函数开始运行
    mylog函数开始运行
    start
    2秒结束了
    一共花费了2.003144秒时间
    end
    """
    time.sleep(2)
    print("%d秒结束了" % (2,))


sleep_more()


def add(func):
    def inner():
        x = func()
        x = x + 1
        print("add方法执行,x:", x)
        return x

    return inner


def cube(func):
    def inner():
        x = func()
        x = x * x * x
        print("cube方法执行,x:", x)
        return x

    return inner


def square(func):
    def inner():
        x = func()
        x = x * x
        print("square方法执行,x:", x)
        return x

    return inner


# 多装饰器demo2,先square,再cube,最后add
@add
@cube
@square
def test():
    """
    square方法执行,x: 4
    cube方法执行,x: 64
    add方法执行,x: 65
    65
    """
    return 2


print(test())

# 带参数的装饰器
print("", sep="\n")
print("#" * 5, "带参数的装饰器", "#" * 5, sep=" ")


def logger(msg):
    def time_master(func):
        def inner():
            start = time.time()
            func()
            end = time.time()
            print(f"{msg}函数执行耗时{end - start:.4f}")

        return inner

    return time_master


@logger(msg="my_fun")
def my_fun():
    """
    my_fun正在执行
    my_fun函数执行耗时1.0109
    """
    print("my_fun正在执行")
    time.sleep(1)


my_fun()  # 等于没有装饰器时的调用 logger(msg="my_fun")(my_fun)()

 

标签:return,Python,inner,func,time,print,装饰,def
From: https://www.cnblogs.com/gongxr/p/17071589.html

相关文章

  • Python之生成器
    """生成器说明:1、生成器一次只返回一个数据;2、yield把函数变成了一个生成器;3、生成器函数的执行过程看起来就是不断地执行->中断->执行->中断的过程;4、一开始,调用......
  • Python之高阶函数
    #高阶函数functoolsimportfunctools#遍历序列元素为参数依次应用到函数中,最终返回累计的结果n=functools.reduce(lambdax,y:x+y,[1,2,3,4,5])print(......
  • [Python] 用描述符实现复用@property方法
    1Python内置的@property机制弊端在于不方便复用不能把它所修饰方法中的逻辑,套用在同一个类中的其他属性上。例如,编写一个类记录分数classGrade:def__init__(s......
  • 【Python基础学习】7.文件和数据格式化
    主要参考来源:慕课嵩天老师的“Python语言程序设计”[https://www.icourse163.org/course/BIT-268001?tid=1468130447]格式化包括字符串格式化和数据格式化字符串格式化:......
  • Python批量改文件名
    对以下路径中的文件名批量修改。一、读取指定路径中的文件名#导入标准库importos#读取文件名filesDir="路径……"fileNameList=os.listdir(filesDir)#输......
  • python-Couldn‘t find a tree builder with the features you requested: lxml
    执行BeautifulSoup(content,features='lxml')时报错,按照网上的方法安装lxml、重新安装lxml、安装指定版本lxml,都无效。最后发现只是PyCharm设置中project的pyth......
  • Python语言基础—常用运算符总结
    系列文章目录......
  • 2021年最新Python讲义:面向对象(OOP)基本概念
    面向对象(OOP)基本概念面向对象编程——​​ObjectOrientedProgramming​​​简写​​OOP​​目标了解面向对象基本概念01.面向对象基本概念我们之前学习的编程方......
  • 终于把Python库全部整理出来了,非常全面!
    Python库汇总篇!建议先马后看~文章目录​​前言​​​​学习爬虫需要掌握哪些库呢?​​​​通用​​​​网络爬虫框架​​​​HTML/XML解析器​​​​浏览器自动化与仿真​​......
  • Python 中的模块
    Python模块是一个Python文件,定义了各种功能接口。把复杂的功能封装为模块(又称为库),将功能实现的细节隐藏起来,使用该模块(库)的程序员不需要了解实现的细节。通过调用模块封......