转自:http://www.cnblogs.com/SeasonLee/archive/2010/04/24/1719444.html

一些往事

  在正式进入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)

  在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(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)

  结果是:

Salesgirl:Hello, what do you want? try_this_shirt
I: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还不算合格,她只会给客人打招呼,但是客人要是买衣服了,也不会给他报价;客人不买的话,也应该推荐其他款式!


  会报价的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

  结果是:

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总算是合格了,但离出色还很远,称职的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

  结果是:

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

Python之美--Decorator深入详解的更多相关文章

  1. python设计模式之装饰器详解(三)

    python的装饰器使用是python语言一个非常重要的部分,装饰器是程序设计模式中装饰模式的具体化,python提供了特殊的语法糖可以非常方便的实现装饰模式. 系列文章 python设计模式之单例模 ...

  2. Python安装、配置图文详解(转载)

    Python安装.配置图文详解 目录: 一. Python简介 二. 安装python 1. 在windows下安装 2. 在Linux下安装 三. 在windows下配置python集成开发环境(I ...

  3. 【和我一起学python吧】Python安装、配置图文详解

     Python安装.配置图文详解 目录: 一. Python简介 二. 安装python 1. 在windows下安装 2. 在Linux下安装 三. 在windows下配置python集成开发环境( ...

  4. Python中的高级数据结构详解

    这篇文章主要介绍了Python中的高级数据结构详解,本文讲解了Collection.Array.Heapq.Bisect.Weakref.Copy以及Pprint这些数据结构的用法,需要的朋友可以参考 ...

  5. [转]使用python来操作redis用法详解

    转自:使用python来操作redis用法详解 class CommRedisBase(): def __init__(self): REDIS_CONF = {} connection_pool = ...

  6. Python中格式化format()方法详解

    Python中格式化format()方法详解 Python中格式化输出字符串使用format()函数, 字符串即类, 可以使用方法; Python是完全面向对象的语言, 任何东西都是对象; 字符串的参 ...

  7. Python调用windows下DLL详解

    Python调用windows下DLL详解 - ctypes库的使用 2014年09月05日 16:05:44 阅读数:6942 在python中某些时候需要C做效率上的补充,在实际应用中,需要做部分 ...

  8. Python操作redis字符串(String)详解 (三)

    # -*- coding: utf-8 -*- import redis #这个redis不能用,请根据自己的需要修改 r =redis.Redis(host=") 1.SET 命令用于设置 ...

  9. 【Python】Python内置函数dir详解

    1.命令介绍 最近学习并使用了一个python的内置函数dir,首先help一下: 复制代码代码如下: >>> help(dir)Help on built-in function ...

随机推荐

  1. 如何使用PullToRefresh

    这里有详解 PullToRefresh使用详解(一)--构建下拉刷新的listView PullToRefresh使用详解(二)---重写BaseAdapter实现复杂XML下拉刷新 PullToRe ...

  2. js小练习去掉指定的字符组成一句话输出

    今天在codewar做练习题时,要求写一个函数把一个字符串去掉WUB这些多余的字符然后把剩下的组成一句话输出,如传入"WUBAWUBBWUBCWUB"后返回"A B C& ...

  3. Html中自定义鼠标的形状

    Html中自定义鼠标的形状 <html> <head> <title>自定义的鼠标形状</title> <meta http-equiv=&quo ...

  4. coreseek安装

    一.  Sphinx简介 Sphinx是由俄罗斯人Andrew Aksyonoff开发的一个全文检索引擎.意图为其他应用提供高速.低空间占用.高结果 相关度的全文搜索功能.Sphinx可以非常容易的与 ...

  5. 【原创】PageAdminCMS 前台SQL注入漏洞(2)

    之前根据公司的要求找了几个web程序的漏洞提交CNVVD,发现漏洞提交上去两个月了,CNVVD却没有任何回应,我提交的这几个漏洞却悄悄的修补掉了. 文章作者:rebeyond 受影响版本:V3.0 漏 ...

  6. 【转】[Intel/Nvidia]Ubuntu 16.04 LTS Intel/Nvidia双显卡切换

    1.在Unity中搜索 "Additional Drivers" 2.打开并选择以下选项 3.打开终端并输入 sudo apt-get install nvidia-361 4.安 ...

  7. c#日期格式化

    系统格式化  符号   语法 示例(2016-05-09 13:09:55:2350) 格式说明 y DateTime.Now.ToString() 2016/5/9 13:09:55 短日期 长时间 ...

  8. Linux启动界面切换:图形界面-字符界面(转)

    Linux字符界面切换到图形界面 由字符界面切换到图形界面可用两种简单方法实现: 1.在字符界面输入startx或init 5 . 2.通过编辑/etc/inittab文件实现默认进入图形界面. 把其 ...

  9. 利用vim查看日志,快速定位问题

    起因 在一般的情况下,如果开发过程中测试报告了一个问题,我一般会这么做: 1.在自己的开发环境下重试一下测试的操作,看看能不能重现问题.不行转2 2.数据库连接池改成测试库的地址,在自己的开发环境下重 ...

  10. 学习MySQL之数据类型(四)

    一.   整数类型: 整数类型 占用字节 最小值 最大值 TINYINT 1 有符号 -128 无符号0 有符号127 无符号255 SMALLINT 2 有符号-3 2768 无符号0 有符号3 2 ...