python decorator(装饰器)

本文深入探讨了Python中装饰器的概念及应用,通过实例演示了如何使用装饰器为现有函数添加额外的功能,而不改变原有函数的结构。装饰器是一种强大的工具,能够帮助开发者以简洁的方式增强代码的功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Python的修饰器的英文名叫Decorator,主要作用是对一个已有的模块做一些“修饰工作”,所谓修饰工作就是想给现有的模块加上一些小装饰(一些小功能,这些小功能可能好多模块都会用到),但又不让这个小装饰(小功能)侵入到原有的模块中的代码里去。

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

def decorator_1(func):
    print 'decorator_1 called'
    def wrapper(*arg):
        print 'before %s' % func.__name__
        func(*arg)
        print 'after %s' % func.__name__
    return wrapper
     
def decorator_2(arg):
    print 'decorator_2 called, with ', arg
    def _decorator(func):
        print '_decorator_2 called'
        def wrapper(*arg):
            print 'before %s' % func.__name__
            func(*arg)
            print 'after %s' % func.__name__
        return wrapper
    return _decorator

def decorator_3(arg):
    print 'decorator_3 called, with ', arg
    def _decorator(func):
        print '_decorator_3 called'
        def wrapper(*arg):
            print 'before %s' % func.__name__
            func(*arg)
            print 'after %s' % func.__name__
        return wrapper
    return _decorator

@decorator_3('d3')   
@decorator_2('d2')   
@decorator_1   
def func(*arg):
    print 'func called with ', arg

if __name__ == "__main__":
    #等价于 decorator_3('d3')(decorator_2('d2')(decorator_1(func)))('arg1', 'arg2')
    func('arg1', 'arg2')

输出:

decorator_3 called, with  d3
decorator_2 called, with  d2
decorator_1 called
_decorator_2 called
_decorator_3 called
before wrapper
before wrapper
before func
func called with  ('arg1', 'arg2')
after func
after wrapper
after wrapper

注意输出顺序

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值