Python之裝飾器

2021-07-27 09:29 更新

裝飾器是由函數(shù)去生成的,用于裝飾某個(gè)函數(shù)或者方法或者類,他可以讓這個(gè)函數(shù)在執(zhí)行之前或者執(zhí)行之后做一些操作。

實(shí)例

先定義一個(gè)函數(shù)func

  1. #!/usr/bin/env python

  2. # _*_ coding: utf-8 _*_

  3. def func(arg):  # 接受一個(gè)參數(shù)arg

  4.    print(arg)  # 輸出這個(gè)參數(shù)

  5. func("Hello World!")  # 調(diào)用腳本并且傳入?yún)?shù)

執(zhí)行腳本,輸出的結(jié)果為:

  1. C:\Python35\python.exe F:/Python_code/Note/裝飾器.py

  2. Hello World!

  3. Process finished with exit code 0

現(xiàn)要在執(zhí)行func這個(gè)函數(shù)前后執(zhí)行一些操作,就可以創(chuàng)建一個(gè)裝飾器來(lái)實(shí)現(xiàn):

  1. #!/usr/bin/env python

  2. # _*_ coding: utf-8 _*_

  3. def decorator(func):  # 創(chuàng)建一個(gè)裝飾器函數(shù),接受的參數(shù)arg參數(shù)就是func函數(shù)名

  4.    def inner(*args, **kwargs):

  5.        print("執(zhí)行函數(shù)之前")

  6.        ret = func(*args, **kwargs)

  7.        print("執(zhí)行函數(shù)之后")

  8.        return ret

  9.    return inner

  10. @decorator  # 如果要讓某個(gè)函數(shù)使用裝飾器,只需要在這個(gè)函數(shù)上面加上@+裝飾器名

  11. def func(arg):

  12.    print(arg)

  13. func("Hello World!")

輸出結(jié)果為:

  1. /usr/bin/python3.5 /home/ansheng/Documents/PycharmProjects/blogcodes/裝飾器.py

  2. 執(zhí)行函數(shù)之前

  3. Hello World!

  4. 執(zhí)行函數(shù)之后

  5. Process finished with exit code 0

多個(gè)裝飾器裝飾同一個(gè)函數(shù)

  1. #!/usr/bin/env python

  2. # _*_ coding: utf-8 _*_

  3. def decorator1(func):

  4.    def inner():

  5.        print("開始之前執(zhí)行裝飾器01")

  6.        ret = func()

  7.        print("結(jié)束之后執(zhí)行裝飾器01")

  8.        return ret

  9.    return inner

  10. def decorator2(func):

  11.    def inner():

  12.        print("decorator2>>>Start...")

  13.        ret = func()

  14.        print("decorator2>>>End...")

  15.        return ret

  16.    return inner

  17. @decorator1

  18. @decorator2

  19. def index():

  20.    print("執(zhí)行函數(shù)...")

  21. index()

輸出結(jié)果:

  1. /usr/bin/python3.5 /home/ansheng/Documents/PycharmProjects/blogcodes/裝飾器.py

  2. 開始之前執(zhí)行裝飾器01

  3. decorator2>>>Start...

  4. 執(zhí)行函數(shù)...

  5. decorator2>>>End...

  6. 結(jié)束之后執(zhí)行裝飾器01

  7. Process finished with exit code 0

更多實(shí)例

  1. #!/usr/bin/env python

  2. # _*_ coding:utf-8 _*_

  3. # Created by 安生 on 2017/2/9

  4. """

  5. 函數(shù)裝飾器

  6. """

  7. def decorator(func):

  8.    def wrapped(*args, **kwargs):

  9.        return func(*args, **kwargs)

  10.    return wrapped

  11. @decorator

  12. def func(a, b):

  13.    return a + b

  14. print(func(1, 2))

  15. """

  16. 類裝飾器

  17. """

  18. class decorator:

  19.    def __init__(self, func):

  20.        self.func = func

  21.    def __call__(self, *args, **kwargs):

  22.        return self.func(*args, **kwargs)

  23. @decorator

  24. def func(a, b):

  25.    return a + b

  26. print(func(1, 2))

  27. """

  28. 帶參數(shù)的函數(shù)裝飾器

  29. """

  30. def parameter(a, b):

  31.    print(a, b)

  32.    def decorator(func):

  33.        def wrapped(*args, **kwargs):

  34.            return func(*args, **kwargs)

  35.        return wrapped

  36.    return decorator

  37. @parameter(1, 2)

  38. def func(a, b):

  39.    return a + b

  40. print(func(10, 20))

  41. """

  42. 帶參數(shù)的類裝飾器

  43. """

  44. def parameter(a, b):

  45.    print(a + b)

  46.    class decorator:

  47.        def __init__(self, func):

  48.            self.func = func

  49.        def __call__(self, *args, **kwargs):

  50.            return self.func(*args, **kwargs)

  51.    return decorator

  52. @parameter(1, 2)

  53. def func(a, b):

  54.    return a + b

  55. print(func(10, 20))

  56. """

  57. 帶參數(shù)的類裝飾器

  58. """

  59. def parameter(a, b):

  60.    print(a, b)

  61.    def decorator(cls):

  62.        class wrapped:

  63.            def __init__(self, *args, **kwargs):

  64.                self.cls = cls(*args, **kwargs)

  65.            def __getattr__(self, item):

  66.                return getattr(self.cls, item)

  67.        return wrapped

  68.    return decorator

  69. @parameter(1, 2)

  70. class CLS:

  71.    def __init__(self):

  72.        self.a = 'a'

  73.    def P(self, v):

  74.        print(v)

  75. obj = CLS()

  76. print(obj.a)

  77. obj.P('Hello,')

  78. """

  79. 為函數(shù)中和類中的方法添加裝飾器

  80. """

  81. def Call(aClass):

  82.    calls = 0

  83.    def onCall(*args, **kwargs):

  84.        nonlocal calls

  85.        calls += 1

  86.        print('call %s to %s' % (calls, func.__name__))

  87.        return aClass(*args, **kwargs)

  88.    return onCall

  89. @Call

  90. def func(a, b):

  91.    return a + b

  92. print(func(1, 2))

  93. class CLS:

  94.    def __init__(self):

  95.        self.a = 'a'

  96.    @Call

  97.    def b(self):

  98.        return self.a

  99. obj = CLS()

  100. print(obj.b())


本文出自 “一盞燭光” 博客,謝絕轉(zhuǎn)載!


以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)