Python之装饰器

2021-07-27 09:29 更新

装饰器是由函数去生成的,用于装饰某个函数或者方法或者类,他可以让这个函数在执行之前或者执行之后做一些操作。

实例

先定义一个函数func

  1. #!/usr/bin/env python

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

  3. def func(arg):  # 接受一个参数arg

  4.    print(arg)  # 输出这个参数

  5. func("Hello World!")  # 调用脚本并且传入参数

执行脚本,输出的结果为:

  1. C:\Python35\python.exe F:/Python_code/Note/装饰器.py

  2. Hello World!

  3. Process finished with exit code 0

现要在执行func这个函数前后执行一些操作,就可以创建一个装饰器来实现:

  1. #!/usr/bin/env python

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

  3. def decorator(func):  # 创建一个装饰器函数,接受的参数arg参数就是func函数名

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

  5.        print("执行函数之前")

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

  7.        print("执行函数之后")

  8.        return ret

  9.    return inner

  10. @decorator  # 如果要让某个函数使用装饰器,只需要在这个函数上面加上@+装饰器名

  11. def func(arg):

  12.    print(arg)

  13. func("Hello World!")

输出结果为:

  1. /usr/bin/python3.5 /home/ansheng/Documents/PycharmProjects/blogcodes/装饰器.py

  2. 执行函数之前

  3. Hello World!

  4. 执行函数之后

  5. Process finished with exit code 0

多个装饰器装饰同一个函数

  1. #!/usr/bin/env python

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

  3. def decorator1(func):

  4.    def inner():

  5.        print("开始之前执行装饰器01")

  6.        ret = func()

  7.        print("结束之后执行装饰器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("执行函数...")

  21. index()

输出结果:

  1. /usr/bin/python3.5 /home/ansheng/Documents/PycharmProjects/blogcodes/装饰器.py

  2. 开始之前执行装饰器01

  3. decorator2>>>Start...

  4. 执行函数...

  5. decorator2>>>End...

  6. 结束之后执行装饰器01

  7. Process finished with exit code 0

更多实例

  1. #!/usr/bin/env python

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

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

  4. """

  5. 函数装饰器

  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. 带参数的函数装饰器

  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. 带参数的类装饰器

  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. 带参数的类装饰器

  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. 为函数中和类中的方法添加装饰器

  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())


本文出自 “一盏烛光” 博客,谢绝转载!


以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号