Python编程 装饰器

  • 作者简介:一名在校计算机学生、每天分享Python的学习经验、和学习笔记。 

  •  座右铭:低头赶路,敬事如仪

  • 个人主页:b网络豆的主页​​​​​​

目录

 前言

一.函数

1.装饰器引入

(1)时间模块

封装函数(calcu_time)

扫描二维码关注公众号,回复: 14565037 查看本文章

2.装饰器介绍

 3.使用装饰器优化


 前言

本章将会讲解Python编程中的装饰器。


一.函数

1.装饰器引入

思考:
  • 计算 test1 运行的时间
  • 计算 test2 运行的时间
  • 计算 test3 运行的时间
  • 计算 test4 运行的时间

(1)时间模块

time模块提供各种操作时间的函数

说明:一般有两种表示时间的方式:

  1. 第一种是时间戳的方式(相对于1970.1.1 00:00:00以秒计算的偏移量),时间戳是惟一的
  2. 第二种以数组的形式表示即(struct_time),共有九个元素,分别表示,同一个时间戳的struct_time会因为时区不同而不同
import time  # python内置模块,时间模块

封装函数(calcu_time)

# 计算时间得函数
def calcu_time(func):
    start = time.time()
    func()
    end = time.time()
    print(f"spend {end - start}")
# 计算时间得函数
def calcu_time(func):
    start = time.time()
    func()
    end = time.time()
    print(f"spend {end - start}")


def test1():
    print("--test1--")
    time.sleep(2)


def test2():
    print("--test2--")
    time.sleep(2)


calcu_time(test1)
calcu_time(test2)


"""
就是在不改变函数源代码得情况下为函数添加新得功能
"""

2.装饰器介绍

装饰器(Decorator)是Python中一个重要部分,它本质上是一个函数,不同于普通函数,装饰器的返回值是一个函数对象。通过利用装饰器,我们可以让其他函数在不做任何代码改动的情况下增加额外的功能,同时也能够让代码更加简洁。

# 需要给各个函数添加上打印hello world得功能
def print_hw(f):
    print("hello world")
    return f


@print_hw           # @装饰器函数名称     test2 = print_hw(test)
def test():
    sum_li = sum([12, 3, 4])
    print(sum_li)
    return sum_li


@print_hw
def test2():
    print("我是网络豆")


# test2 = print_hw(test)  # test函数引用作为实参 test2 = f = test
# test2()     # test2() = f() = test()


test()
test2()


"""
注意:
1. test()函数未调用得时候,装饰器就已经执行
"""



 3.使用装饰器优化

import time

"""
此处是问题代码,因为重复调用了test1()
"""


 # 计算时间得函数
def calcu_time(func):    # func = test1
     start = time.time()
     func()      # test1()
     end = time.time()
     print(f"spend {end - start}")
     return func


 def test1():
     print("--test1--")
     time.sleep(2)

 test = calcu_time(test1)    # test = func = test1
 test()


# 计算时间得函数
def calcu_time(func):
    def test_in():               # 1.外函数里面有内函数
        start = time.time()
        func()      # test1()    # 2.内函数引用了外函数得临时变量
        end = time.time()
        print(f"spend {end - start}")
    return test_in               # 3.内函数的引用作为外函数的返回值


@calcu_time             # test = calcu_time(test1)
def test1():
    print("--test1--")
    time.sleep(2)


@calcu_time
def test2():
    print("--test2--")
    time.sleep(2)


 test = calcu_time(test1)    # test = test_in
 test()     # test_in()

 test = calcu_time(test2)    # test = test_in
 test()     # test_in()

test1()


"""
此处,形成闭包的现象。
1.嵌套函数
2.内层函数引用外层函数变量-->函数名本质也是变量
3.内函数的引用作为外层函数的返回值
"""

 创作不易,求关注,点赞,收藏,谢谢~  

猜你喜欢

转载自blog.csdn.net/yj11290301/article/details/128793026
今日推荐