Python编程:decorator装饰器

简介: Python编程:decorator装饰器

装饰器:

定义:本质是函数,装饰其他函数,为其他函数添加附加功能

原则:

1、不能修改被装饰的函数源代码

2、不能修改被装饰的函数的调用方式


原理:

1.函数即“变量”

2.高阶函数


a.把函数名当做实参传递给函数

b.返回一个函数名

3.嵌套函数

总结:

高阶函数 + 嵌套函数 =》 装饰器


import time
def timer(arg):  # 可以接收参数
    print("arg:", arg)
    def outerWrapper(func):  # 接收函数参数
        def wrapper(*args, **kwargs):  # 装饰器
            start_time = time.time()
            func(*args, **kwargs)
            end_time = time.time()
            print("run time of func is %s " % (end_time - start_time))
        return wrapper
    return outerWrapper
@timer("foo")  # 等价于: foo = timer(foo)
def foo():  # 无参
    time.sleep(3)
    print("this is foo")
@timer("foo2")
def foo2(name):  # 带参
    time.sleep(3)
    print("this is foo2,name = ", name)
foo()
foo2("Tom")
"""OUT:
arg: foo
arg: foo2
this is foo
run time of func is 3.00019907951355 
this is foo2,name =  Tom
run time of func is 3.000049114227295 
"""

保持原有属性不变

# -*- coding: utf-8 -*-
# @File    : decorator装饰器.py.py
# @Date    : 2018-05-30
# @Author  : Peng Shiyu
from functools import wraps
# 带参装饰器
def log(text):
    print(text)
    # 无参的时候只需要以下代码
    def outter(func):
        print("call outter")
        print(func.__name__)
        # 把原始函数的__name__等属性复制到 inner() 函数中
        @wraps(func)
        def inner(*args, **kwargs):
            print("call inner")
            return func(*args, **kwargs)
        return inner
    return outter
@log("new function")
def hello():
    print("hello world")
hello()
print(hello.__name__)
"""
new function
call outter
hello
call inner
hello world
hello
"""

基于类的装饰器

class Counter:
    def __init__(self, func):
        self.func = func
        self.count = 0
    def __call__(self, *args, **kwargs):
        self.count += 1
        return self.func(*args, **kwargs)
@Counter
def foo():
    pass
for i in range(10):
    foo()
print(foo.count)  # 10

参考:

简述 init、new、call 方法

相关文章
|
2月前
|
测试技术 Python
Python装饰器:为你的代码施展“魔法”
Python装饰器:为你的代码施展“魔法”
264 100
|
3月前
|
设计模式 缓存 监控
Python装饰器:优雅增强函数功能
Python装饰器:优雅增强函数功能
282 101
|
2月前
|
缓存 Python
Python装饰器:为你的代码施展“魔法
Python装饰器:为你的代码施展“魔法
159 88
|
3月前
|
缓存 测试技术 Python
Python装饰器:优雅地增强函数功能
Python装饰器:优雅地增强函数功能
234 99
|
3月前
|
存储 缓存 测试技术
Python装饰器:优雅地增强函数功能
Python装饰器:优雅地增强函数功能
204 98
|
2月前
|
Python
Python编程:运算符详解
本文全面详解Python各类运算符,涵盖算术、比较、逻辑、赋值、位、身份、成员运算符及优先级规则,结合实例代码与运行结果,助你深入掌握Python运算符的使用方法与应用场景。
219 3
|
2月前
|
数据处理 Python
Python编程:类型转换与输入输出
本教程介绍Python中输入输出与类型转换的基础知识,涵盖input()和print()的使用,int()、float()等类型转换方法,并通过综合示例演示数据处理、错误处理及格式化输出,助你掌握核心编程技能。
483 3
|
2月前
|
并行计算 安全 计算机视觉
Python多进程编程:用multiprocessing突破GIL限制
Python中GIL限制多线程性能,尤其在CPU密集型任务中。`multiprocessing`模块通过创建独立进程,绕过GIL,实现真正的并行计算。它支持进程池、队列、管道、共享内存和同步机制,适用于科学计算、图像处理等场景。相比多线程,多进程更适合利用多核优势,虽有较高内存开销,但能显著提升性能。合理使用进程池与通信机制,可最大化效率。
300 3
|
2月前
|
Java 调度 数据库
Python threading模块:多线程编程的实战指南
本文深入讲解Python多线程编程,涵盖threading模块的核心用法:线程创建、生命周期、同步机制(锁、信号量、条件变量)、线程通信(队列)、守护线程与线程池应用。结合实战案例,如多线程下载器,帮助开发者提升程序并发性能,适用于I/O密集型任务处理。
312 0
|
3月前
|
缓存 测试技术 Python
解锁Python超能力:深入理解装饰器
解锁Python超能力:深入理解装饰器
139 2

推荐镜像

更多