设为首页 收藏本站
查看: 1017|回复: 0

[经验分享] Python之美--Decorator深入详解(一)

[复制链接]

尚未签到

发表于 2015-4-20 11:19:39 | 显示全部楼层 |阅读模式
  There should be one—--and preferably only one –--obvious way to do it.
                                                                                ----摘自The Zen of Python, by Time Peters
  


  一些往事

    在正式进入Decorator话题之前,请允许我讲一个小故事。
  在最近的项目开发过程中,一位同事在读我的代码的时候,提出质疑,为什么同样的验证代码要重复出现在服务接口中呢?
    如某服务接口是游戏中的玩家想建造建筑:
  



def build(user, build_name):
    if not is_user_valid(user):
        redirect("/auth/login/")
        return False
    #do something here
    return create_building(build_name)
def build(user, build_name):    if not is_user_valid(user):            redirect("/auth/login/")            return False    #do something here    return create_building(build_na
  在build这个方法中,前3行是用来检测玩家是否已经验证过的,如果是非验证的玩家,就重定向到登陆页面;如果是验证过的玩家,就给他建造他想要的建筑。
  他指出这样的3行验证代码(虽然已经很短)将会出现任意一个玩家服务接口中——升级建筑、拆建筑、甚至是频繁的聊天,我说这只是Ctrl+C、Ctrl+V的时间啊,但是那时候我深想,如果现在需求有变动,要在原来的验证失败的情况下,写日志,那原来的3行代码就变成4行:





if not is_user_valid(user):
    redirect("/auth/login/")
    log_warning(" %s is trying to enter without permission!" %(user["name"]))
    return False
  


  更痛苦的是,你要在每个出现if not is_user_valid(user)的地方增加log_warning这一行,这些时间足够你泡一壶好茶、听完一首《Poker Face》、tweet好几次、甚至修复了一个bug……
    正如文章开头Time Peters所说的那样,总会有一个最好(合适)的方法来完成一件事。之后请教赖总,就祭出Decorator。以下是我基于Decorator改写的验证代码:




def authenticated(method):
    def wrapper(user, *args):
        if not is_user_valid(user):
            redirect("/auth/login/")
            log_warning(" %s is trying to enter without permission!" %(user["name"]))
            return False
        return method(user, *args)
    return wrapper
@authenticated
def build(user, build_name):
    return create_building(build_name)
  
  
  
  
  使用Decorator的好处是玩家服务接口——升级建筑、拆建筑、聊天,需要进行验证的时候,只需要在方法前加上@authenticated就可,更重要的是因需求而对验证失败情况的处理时(如上面讲到的log),并不会影响原有代码的结构,因为你只要在authenticated方法中加入log_warning这一行就搞掂啦!


  毫无疑问Decorator对于维持代码结构起到神一样的作用,下面让我们进入Decorator之旅,PS:如果你已经是Decorator高手,请先别急着Ctrl+W,望不吝赐教,指出笔者在文中的问题和疏漏,不胜感激!
  
  
   初始Decorator
    Decorator,修饰符,是在Python2.4中增加的功能,也是pythoner实现元编程的最新方式,同时它也是最简单的元编程方式。为什么是“最简单”呢?是的,其实在Decorator之前就已经有classmethod()和staticmethod()内置函数,但他们的缺陷是会导致函数名的重复使用(可以看看David Mertz的Charming Python: Decorators make magic easy ),以下是摘自他本人的原文:
class C:    def foo(cls, y):        print "classmethod", cls, y    foo = classmethod



class C:
    def foo(cls, y):
        print "classmethod", cls, y
    foo = classmethod(foo)
  是的,classmethod做的只是函数转换,但是它却让foo这个名字另外出现了2次。记得有一句话是:人类因懒惰而进步。Decorator的诞生,让foo少出现2次。





class C:
    @classmethod
    def foo(cls, y):
        print "classmethod", cls, y
  读者也许已经想到Decorator在python中是怎么处理的了(如果还没头绪的,强烈建议先去看看limodou写的Decorator学习笔记 )。下面我列出4种用法。


  

写法 使用Decorator不使用Decorator
单个Decorator,不带参数@dec
def method(args):
    pass
def method(args):
    pass
method = dec(method)
多个Decorator,不带参数@dec_a
@dec_b
@dec_c
def method(args):
    pass
def method(args):
    pass
method = dec_a(dec_b(dec_c(method)))
单个Decorator,带参数@dec(params)
def method(args):
    pass
def method(args):
    pass
method = dec(params)(method)
多个Decorator,带参数@dec_a(params1)
@dec_b(params2)
@dec_c(params3)
def method(args):
    pass
def method(args):
    pass
method = dec_a(params1)(dec_b(params2)(dec_c(params)(method)))
  
  


  
                                                           单个 Decorator,不带参数
    设想一个情景,你平时去买衣服的时候,跟售货员是怎么对话的呢?售货员会先向你问好,然后你会试穿某件你喜爱的衣服。





def salesgirl(method):
    def serve(*args):
        print "Salesgirl:Hello, what do you want?", method.__name__
        method(*args)
    return serve
@salesgirl
def try_this_shirt(size):
    if size < 35:
        print "I: %d inches is to small to me" %(size)
    else:
        print "I:%d inches is just enough" %(size)
try_this_shirt(38)
  

def salesgirl(method):    def serve(*args):        print "Salesgirl:Hello, what do you want?", method.__name__        method(*args)    return serve   @salesgirldef try_this_shirt(size):    if size < 35:        print "I: %d inches is to small to me" %(size)    else:        print "I:%d inches is just enough" %(size)try_this_shirt(
  结果是:





Salesgirl:Hello, what do you want? try_this_shirt
I:38 inches is just enough
  

Salesgirl:Hello, what do you want? try_this_shirtI:38 inches is just enough   
    这只是一个太简单的例子,以至一些“细节”没有处理好,你试穿完了好歹也告诉salesgirl到底要不要买啊。。。这样try_this_shirt方法需要改成带返回值 (假设是bool类型,True就是要买,False就是不想买),那么salesgirl中的serve也应该带返回值,并且返回值就是 method(*args)。

  

修改后的salesgirl   
  




def salesgirl(method):
    def serve(*args):
        print "Salesgirl:Hello, what do you want?", method.__name__
        return method(*args)
    return serve
@salesgirl
def try_this_shirt(size):
    if size < 35:
        print "I: %d inches is to small to me" %(size)
        return False
    else:
        print "I:%d inches is just enough" %(size)
        return True
result = try_this_shirt(38)
print "Mum:do you want to buy this?", result
    结果是:





Salesgirl:Hello, what do you want? try_this_shirt
I:38 inches is just enough
Mum:do you want to buy this? True
  

Salesgirl:Hello, what do you want? try_this_shirtI:38 inches is just enoughMum:do you want to buy this? True  


  
    现在我们的salesgirl还不算合格,她只会给客人打招呼,但是客人要是买衣服了,也不会给他报价;客人不买的话,也应该推荐其他款式!


    会报价的salesgirl:





def salesgirl(method):
    def serve(*args):
        print "Salesgirl:Hello, what do you want?", method.__name__
        result = method(*args)
        if result:
            print "Salesgirl: This shirt is 50$."
        else:
            print "Salesgirl: Well, how about trying another style?"
        return result
    return serve
@salesgirl
def try_this_shirt(size):
    if size < 35:
        print "I: %d inches is to small to me" %(size)
        return False
    else:
        print "I:%d inches is just enough" %(size)
        return True
result = try_this_shirt(38)
print "Mum:do you want to buy this?", result
  

def salesgirl(method):    def serve(*args):        print "Salesgirl:Hello, what do you want?", method.__name__        result = method(*args)        if result:            print "Salesgirl: This shirt is 50$."        else:            print "Salesgirl: Well, how about trying another style?"        return result    return serve   @salesgirldef try_this_shirt(size):    if size < 35:        print "I: %d inches is to small to me" %(size)        return False    else:        print "I:%d inches is just enough" %(size)        return Trueresult = try_this_shirt(38)print "Mum:do you want to buy this?", resul
  结果是:
  





Salesgirl:Hello, what do you want? try_this_shirt
I:38 inches is just enough
Salesgirl: This shirt is 50$.
Mum:do you want to buy this? True
  

Salesgirl:Hello, what do you want? try_this_shirtI:38 inches is just enoughSalesgirl: This shirt is 50$.Mum:do you want to buy this? True
    这样的salesgirl总算是合格了,但离出色还很远,称职的salesgirl是应该对熟客让利,老用户总得有点好处吧?
  


  单个 Decorator,带参数
  会报价并且带折扣的salesgirl:





def salesgirl(discount):
    def expense(method):
        def serve(*args):
            print "Salesgirl:Hello, what do you want?", method.__name__
            result = method(*args)
            if result:
                print "Salesgirl: This shirt is 50$.As an old user, we promised to discount at %d%%" %(discount)
            else:
                print "Salesgirl: Well, how about trying another style?"
            return result
        return serve
    return expense
@salesgirl(50)
def try_this_shirt(size):
    if size < 35:
        print "I: %d inches is to small to me" %(size)
        return False
    else:
        print "I:%d inches is just enough" %(size)
        return True
result = try_this_shirt(38)
print "Mum:do you want to buy this?", result
  

def salesgirl(discount):    def expense(method):        def serve(*args):            print "Salesgirl:Hello, what do you want?", method.__name__            result = method(*args)            if result:                print "Salesgirl: This shirt is 50$.As an old user, we promised to discount at %d%%" %(discount)            else:                print "Salesgirl: Well, how about trying another style?"            return result        return serve    return expense   @salesgirl(50)def try_this_shirt(size):    if size < 35:        print "I: %d inches is to small to me" %(size)        return False    else:        print "I:%d inches is just enough" %(size)        return Trueresult = try_this_shirt(38)print "Mum:do you want to buy this?", result  
  结果是:
  





Salesgirl:Hello, what do you want? try_this_shirt
I:38 inches is just enough
Salesgirl: This shirt is 50$.As an old user, we promised to discount at 50%
Mum:do you want to buy this? True
  

Salesgirl:Hello, what do you want? try_this_shirtI:38 inches is just enoughSalesgirl: This shirt is 50$.As an old user, we promised to discount at 50%Mum:do you want to buy this? True   

    这里定义的salesgirl是会给客户50%的折扣,因为salesgirl描述符是带参数,而参数就是折扣。如果你是第一次看到这个 salesgirl,会被她里面嵌套的2个方法而感到意外,没关系,当你习惯了Decorator之后,一切都变得很亲切啦。


  未完,待续
    上面这些也只是一个开胃汤,在下一篇正餐中,我将带来更多Decorator的高级用法,敬请留意。

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-58774-1-1.html 上篇帖子: python技巧31[pythonTips1] 下篇帖子: ruby/python/java全覆盖的Selenium-Webdriver系列教程(1)————快速开始
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表