python closure and function decorators 2

好吧,基礎打好,聊聊decorator,先看這段代碼:app

def SayHi(name):
    return "How are you {0}, good morning".format(name)

def decoator(func):
    def func_wrapper(name):
        return "<p>{0}</p>".format(func(name))
    return func_wrapper

hi = decoator(SayHi)
print hi("Allen")

當咱們每次調用hi()方法的時候,你不以爲特別方便麼?函數

不少人會問,爲啥要用decoator?請想一想,再增長一個返回<div></div>的函數是否是更方便spa

 

好了,下面說點語法糖,用到@函數修飾code

def decoator(func):
    def func_wrapper(name):
        return "<p>{0}</p>".format(func(name))
    return func_wrapper

@decoator
def SayHi(name):
    return "How are you {0}, good morning".format(name)

print SayHi("Allen")

代碼幾乎沒變,卻更乾淨,整潔,優雅了orm

 

更多的時候,不少人這麼使用decorator,是否是很舒服? blog

class Decorate:
    def decorate(self,func):
        def func_wrapper(self):
            return "<p>{0}</p>".format(func(self))
        return func_wrapper

class Person(object):
    d = Decorate()
    def __init__(self):
        self.name = "Allen"
        self.family = "Liu"

    @d.decorate
    def get_fullname(self):
        return self.name+" "+self.family

my_person = Person()
print my_person.get_fullname()<p>Allen Liu</p>
相關文章
相關標籤/搜索