Python プログラミング デコレータ

  • 著者について: 学校のコンピュータ学生で、Python の学習経験と学習ノートを毎日共有しています。 

  •  モットー:頭を下げて急いで道を進み、敬意を払う

  • 個人ホームページ:bネットワーク堂のホームページ

目次

 序文

1.機能

1. デコレータの紹介

(1) 時間モジュール

ラッパー関数 (calcu_time)

2. デコレータの紹介

 3. デコレータの最適化を使用する


 序文

この章では、Python プログラミングのデコレータについて説明します。


1.機能

1. デコレータの紹介

考える:
  • test1 の実行時間を計算する
  • test2 の実行時間を計算する
  • test3 の実行時間を計算する
  • test4 の実行時間を計算する

(1) 時間モジュール

time モジュールは、時間を操作するためのさまざまな関数を提供します

説明: 時間を表現するには、一般に次の 2 つの方法があります。

  1. 1 つ目はタイムスタンプの方法 (1970.1.1 00:00:00 からの秒数で計算されたオフセット) で、タイムスタンプは一意です。
  2. 2 つ目は配列 (struct_time) の形式で表現され、合計 9 つの要素があり、タイム ゾーンが異なると同じタイムスタンプの 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. デコレータの紹介

デコレータは 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