首页 > 代码库 > python closure and function decorators 2

python closure and function decorators 2

好吧,基础打好,聊聊decorator,先看这段代码:

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_wrapperhi = decoator(SayHi)print hi("Allen")

当我们每次调用hi()方法的时候,你不觉得特别方便么?

很多人会问,为啥要用decoator?请想想,再增加一个返回<div></div>的函数是不是更方便

 

好了,下面说点语法糖,用到@函数修饰

def decoator(func):    def func_wrapper(name):        return "<p>{0}</p>".format(func(name))    return func_wrapper@decoatordef SayHi(name):    return "How are you {0}, good morning".format(name)print SayHi("Allen")

代码几乎没变,却更干净,整洁,优雅了

 

更多的时候,很多人这么使用decorator,是不是很舒服? 

class Decorate:    def decorate(self,func):        def func_wrapper(self):            return "<p>{0}</p>".format(func(self))        return func_wrapperclass Person(object):    d = Decorate()    def __init__(self):        self.name = "Allen"        self.family = "Liu"    @d.decorate    def get_fullname(self):        return self.name+" "+self.familymy_person = Person()print my_person.get_fullname()

<p>Allen Liu</p>

 

python closure and function decorators 2