别院牧志知识库 别院牧志知识库
首页
  • 基础

    • 全栈之路
    • 😎Awesome资源
  • 进阶

    • Python 工匠系列
    • 高阶知识点
  • 指南教程

    • Socket 编程
    • 异步编程
    • PEP 系列
  • 面试

    • Python 面试题
    • 2025 面试记录
    • 2022 面试记录
    • 2021 面试记录
    • 2020 面试记录
    • 2019 面试记录
    • 数据库索引原理
  • 基金

    • 基金知识
    • 基金经理
  • 细读经典

    • 德隆-三个知道
    • 孔曼子-摊大饼理论
    • 配置者说-躺赢之路
    • 资水-建立自己的投资体系
    • 反脆弱
  • Git 参考手册
  • 提问的智慧
  • 分类
  • 标签
  • 归档
GitHub (opens new window)
首页
  • 基础

    • 全栈之路
    • 😎Awesome资源
  • 进阶

    • Python 工匠系列
    • 高阶知识点
  • 指南教程

    • Socket 编程
    • 异步编程
    • PEP 系列
  • 面试

    • Python 面试题
    • 2025 面试记录
    • 2022 面试记录
    • 2021 面试记录
    • 2020 面试记录
    • 2019 面试记录
    • 数据库索引原理
  • 基金

    • 基金知识
    • 基金经理
  • 细读经典

    • 德隆-三个知道
    • 孔曼子-摊大饼理论
    • 配置者说-躺赢之路
    • 资水-建立自己的投资体系
    • 反脆弱
  • Git 参考手册
  • 提问的智慧
  • 分类
  • 标签
  • 归档
GitHub (opens new window)
  • 辨析

  • Sockets编程

  • Django

  • stackoverflow

  • Flask

  • 全栈之路

    • 基础篇

    • 进阶篇

      • Python 全栈之路系列之迭代器与生成器
      • Python 全栈之路系列之装饰器
        • 实例
        • 多个装饰器装饰同一个函数
        • 更多实例
      • Python 标准库系列之模块默认全局变量
      • Python 全栈之路系列之异常处理
      • Python 全栈之路系列之文件操作
      • Python 全栈之路系列之递归
      • Python 全栈之路系列之反射
      • Python 全栈之路系列之正则表达式 re 模块
      • Python 全栈之路系列之字符串格式化
    • 面向对象

    • 网络编程

    • 操作系统

    • 标准库

    • 第三方库

    • Python 全栈之路
  • 面试

  • 代码片段

  • 异步编程

  • 😎Awesome资源

  • PEP

  • Python工匠系列

  • 高阶知识点

  • Python 学习资源待整理
  • 设计模式

  • 好“艹蛋”的 Python 呀!
  • FIFO | 待学清单📝
  • pip 安装及使用
  • 数据分析

  • 源码阅读计划

  • OOP

  • 关于 python 中的 setup.py
  • 并行分布式框架 Celery
  • 七种武器,让你的代码提高可维护性
  • 使用 pdb 调试 Python 代码
  • 每周一个 Python 标准库
  • 🐍Python
  • 全栈之路
  • 进阶篇
佚名
2020-05-23
目录

Python 全栈之路系列之装饰器

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

# 实例

先定义一个函数func

#!/usr/bin/env python
# _*_ coding: utf-8 _*_

def func(arg):  # 接受一个参数arg
    print(arg)  # 输出这个参数

func("Hello World!")  # 调用脚本并且传入参数
1
2
3
4
5
6
7

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

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

Process finished with exit code 0
1
2
3
4

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

#!/usr/bin/env python
# _*_ coding: utf-8 _*_

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

    def inner(*args, **kwargs):
        print("执行函数之前")
        ret = func(*args, **kwargs)
        print("执行函数之后")
        return ret

    return inner

@decorator  # 如果要让某个函数使用装饰器,只需要在这个函数上面加上@+装饰器名
def func(arg):
    print(arg)

func("Hello World!")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

输出结果为:

/usr/bin/python3.5 /home/ansheng/Documents/PycharmProjects/blogcodes/装饰器.py
执行函数之前
Hello World!
执行函数之后

Process finished with exit code 0
1
2
3
4
5
6

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

#!/usr/bin/env python
# _*_ coding: utf-8 _*_

def decorator1(func):
    def inner():
        print("开始之前执行装饰器01")
        ret = func()
        print("结束之后执行装饰器01")
        return ret

    return inner


def decorator2(func):
    def inner():
        print("decorator2>>>Start...")
        ret = func()
        print("decorator2>>>End...")
        return ret

    return inner


@decorator1
@decorator2
def index():
    print("执行函数...")

index()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29

输出结果:

/usr/bin/python3.5 /home/ansheng/Documents/PycharmProjects/blogcodes/装饰器.py
开始之前执行装饰器01
decorator2>>>Start...
执行函数...
decorator2>>>End...
结束之后执行装饰器01

Process finished with exit code 0
1
2
3
4
5
6
7
8

# 更多实例

#!/usr/bin/env python
# _*_ coding:utf-8 _*_

# Created by 安生 on 2017/2/9

"""
函数装饰器
"""


def decorator(func):
    def wrapped(*args, **kwargs):
        return func(*args, **kwargs)

    return wrapped


@decorator
def func(a, b):
    return a + b


print(func(1, 2))
"""
类装饰器
"""


class decorator:
    def __init__(self, func):
        self.func = func

    def __call__(self, *args, **kwargs):
        return self.func(*args, **kwargs)


@decorator
def func(a, b):
    return a + b


print(func(1, 2))
"""
带参数的函数装饰器
"""


def parameter(a, b):
    print(a, b)

    def decorator(func):
        def wrapped(*args, **kwargs):
            return func(*args, **kwargs)

        return wrapped

    return decorator


@parameter(1, 2)
def func(a, b):
    return a + b


print(func(10, 20))
"""
带参数的类装饰器
"""


def parameter(a, b):
    print(a + b)

    class decorator:
        def __init__(self, func):
            self.func = func

        def __call__(self, *args, **kwargs):
            return self.func(*args, **kwargs)

    return decorator


@parameter(1, 2)
def func(a, b):
    return a + b


print(func(10, 20))

"""
带参数的类装饰器
"""


def parameter(a, b):
    print(a, b)

    def decorator(cls):
        class wrapped:
            def __init__(self, *args, **kwargs):
                self.cls = cls(*args, **kwargs)

            def __getattr__(self, item):
                return getattr(self.cls, item)

        return wrapped

    return decorator


@parameter(1, 2)
class CLS:
    def __init__(self):
        self.a = 'a'

    def P(self, v):
        print(v)


obj = CLS()
print(obj.a)
obj.P('Hello,')

"""
为函数中和类中的方法添加装饰器
"""


def Call(aClass):
    calls = 0

    def onCall(*args, **kwargs):
        nonlocal calls
        calls += 1
        print('call %s to %s' % (calls, func.__name__))
        return aClass(*args, **kwargs)

    return onCall


@Call
def func(a, b):
    return a + b


print(func(1, 2))


class CLS:
    def __init__(self):
        self.a = 'a'

    @Call
    def b(self):
        return self.a


obj = CLS()
print(obj.b())
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
编辑 (opens new window)
#编码#装饰器
上次更新: 2024-07-23, 01:00:43
Python 全栈之路系列之迭代器与生成器
Python 标准库系列之模块默认全局变量

← Python 全栈之路系列之迭代器与生成器 Python 标准库系列之模块默认全局变量→

最近更新
01
2025 面试记录
05-28
02
提升沟通亲和力的实用策略
03-26
03
工作
07-15
更多文章>
Theme by Vdoing | Copyright © 2019-2025 IMOYAO | 别院牧志
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式