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")

 

posted @ 2014-01-11 10:55  Xjng  阅读(750)  评论(0编辑  收藏  举报