Python装饰器笔记

本文介绍了Python中装饰器的基本概念及使用方法,包括无参数和带参数的装饰器应用实例,帮助读者理解如何通过装饰器增强函数功能。
def small(func):
    def getfunc():
        print "<small>"
        func()
        print "</small>"
    return getfunc
def strong(func):
    def getfunc():
        print "<strong>"
        func()
        print "</strong>"
    return getfunc
def text(text="HELLO WORLD"):
    print text
    
# newtext=small(strong(text))
# newtext()

@small
@strong
def text1(text="HELLO WORLD"):
    print text
text1()

 被装饰的函数带参数的范例

#encoding=utf-8
def first(func):
    def _first(hello):
        print "first"
        func(hello)
        print "last"
    return _first
   
@first
def myfunc(hello):
    print hello
myfunc("hello")

 装饰器带参数的范例,这个需要在装饰器定义时多嵌套一层函数:

#encoding=utf-8
def deco(deco_params):
    def _deco(func):
        def _deco(func_params):
            print "first"
            print deco_params
            func(func_params)
            print "last"
        return _deco
    return _deco
       
@deco("params")
def myfunc(func_params):
    print func_params
myfunc("hello")

 

转载于:https://www.cnblogs.com/Xjng/p/3514791.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值