装饰器--棉花糖语法Python

本文介绍了Python装饰器的使用,从编写简单函数开始,逐步讲解如何使用装饰器在函数执行前后添加额外功能,处理带参数的函数,以及如何使装饰器接受参数和类参数。通过实例展示了装饰器的工作原理,并分享了作者在学习过程中的心得。

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

最近很多人问我关于Python装饰器的问题,我把它总结成blog方便他人和自己。

借鉴了这篇关于装饰器的博文,http://www.cnblogs.com/rhcad/archive/2011/12/21/2295507.html。同时加入了自己的补充和心得。

我用Python IDE来调试,用了Python3.4.2。输出用>>>表示。

第一步:编写一个最简单的函数

#!/usr/bin/env python
def myfunc():
    print('myfunc() called')
myfunc()
>>>myfunc() called

第二步:使用装饰函数在函数执行前后分别附加额外功能

#!/usr/bin/env python
def deco(func):
    print('before myfunc() called')
    func()
    print('after myfunc() called')
    return func

def myfunc():
    print('myfunc() called')
    
deco(myfunc)
>>>before myfunc() called
>>>myfunc() called
>>>after myfunc() called

如果调用函数改为:

myfunc = deco(myfunc)
myfunc()
>>>before myfunc() called
>>>myfunc() called
>>>after myfunc() called
>>>myfunc() called          <====myfunc()的输出

如果调用函数改为:

myfunc = deco(myfunc)
>>>before myfunc() called
>>>myfunc() called
>>>after myfunc() called

第三步:使用棉花糖@语法来装饰函数

#!/usr/bin/env python
def deco(func):
    print('before myfunc() called')
    func()
    print('after myfunc() called')
    return func

@deco
def myfunc():
    print('myfunc() called')
    
myfunc()
>>>before myfunc() called
>>>myfunc() called
>>>after myfunc() called
>>>myfunc() called          
解析:调用myfunc(),实际上等于 deco(myfunc)()

如果改为:


                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值