Python中用Decorator来简化元编程的教程


Posted in Python onApril 13, 2015

少劳多得

Decorator 与 Python 之前引入的元编程抽象有着某些共同之处:即使没有这些技术,您也一样可以实现它们所提供的功能。正如 Michele Simionato 和我在 可爱的 Python 专栏的早期文章 中指出的那样,即使在 Python 1.5 中,也可以实现 Python 类的创建,而不需要使用 “元类” 挂钩。

Decorator 根本上的平庸与之非常类似。Decorator 所实现的功能就是修改紧接 Decorator 之后定义的函数和方法。这总是可能的,但这种功能主要是由 Python 2.2 中引入的 classmethod() 和 staticmethod() 内置函数驱动的。在旧式风格中,您可以调用 classmethod(),如下所示:
清单 1. 典型的 “旧式” classmethod

class C:
  def foo(cls, y):
    print "classmethod", cls, y
  foo = classmethod(foo)

虽然 classmethod() 是内置函数,但并无独特之处;您也可以使用自己的方法转换函数。例如:
清单 2. 典型的 “旧式” 方法的转换

def enhanced(meth):
  def new(self, y):
    print "I am enhanced"
    return meth(self, y)
  return new
class C:
  def bar(self, x):
    print "some method says:", x
  bar = enhanced(bar)

decorator 所做的一切就是使您避免重复使用方法名,并且将 decorator 放在方法定义中第一处提及其名称的地方。例如:
清单 3. 典型的 “旧式” classmethod

class C:
  @classmethod
  def foo(cls, y):
    print "classmethod", cls, y
  @enhanced
  def bar(self, x):
    print "some method says:", x

decorator 也可以用于正则函数,采用的是与类中的方法相同的方式。令人惊奇的是,这一切是如此简单(严格来说,甚至有些不必要),只需要对语法进行简单修改,所有东西就可以工作得更好,并且使得程序的论证更加轻松。通过在方法定义的函数之前列出多个 decorator,即可将 decorator 链接在一起;良好的判断可以有助于防止将过多 decorator 链接在一起,不过有时候将几个 decorator 链接在一起是有意义的:
清单 4. 链接 decorator

@synchronized
@logging
def myfunc(arg1, arg2, ...):
  # ...do something
# decorators are equivalent to ending with:
#  myfunc = synchronized(logging(myfunc))
# Nested in that declaration order

Decorator 只是一个语法糖,如果您过于急切,那么它就会使您搬起石头砸了自己的脚。decorator 其实就是一个至少具有一个参数的函数 —— 程序员要负责确保 decorator 的返回内容仍然是一个有意义的函数或方法,并且实现了原函数为使连接有用而做的事情。例如,下面就是 decorator 两个不正确的用法:
清单 5. 没有返回函数的错误 decorator

>>> def spamdef(fn):
...   print "spam, spam, spam"
...
>>> @spamdef
... def useful(a, b):
...   print a**2 + b**2
...
spam, spam, spam
>>> useful(3, 4)
Traceback (most recent call last):
 File "<stdin>", line 1, in ?
TypeError: 'NoneType' object is not callable

decorator 可能会返回一个函数,但这个函数与未修饰的函数之间不存在有意义的关联:
清单 6. 忽略传入函数的 decorator

>>> def spamrun(fn):
...   def sayspam(*args):
...     print "spam, spam, spam"
...   return sayspam
...
>>> @spamrun
... def useful(a, b):
...   print a**2 + b**2
...
>>> useful(3,4)
spam, spam, spam

最后,一个表现更良好的 decorator 可以在某些方面增强或修改未修饰函数的操作:
清单 7. 修改未修饰函数行为的 decorator

>>> def addspam(fn):
...   def new(*args):
...     print "spam, spam, spam"
...     return fn(*args)
...   return new
...
>>> @addspam
... def useful(a, b):
...   print a**2 + b**2
...
>>> useful(3,4)
spam, spam, spam
25

您可能会质疑,useful() 到底有多么有用?addspam() 真的是那样出色的增强 吗?但这种机制至少符合您通常能在有用的 decorator 中看到的那种模式。

高级抽象简介

根据我的经验,元类应用最多的场合就是在类实例化之后对类中的方法进行修改。decorator 目前并不允许您修改类实例化本身,但是它们可以修改依附于类的方法。这并不能让您在实例化过程中动态添加或删除方法或类属性,但是它让这些方法可以在运行时根据环境的条件来变更其行为。现在从技术上来说,decorator 是在运行 class 语句时应用的,对于顶级类来说,它更接近于 “编译时” 而非 “运行时”。但是安排 decorator 的运行时决策与创建类工厂一样简单。例如:
清单 8. 健壮但却深度嵌套的 decorator

def arg_sayer(what):
  def what_sayer(meth):
    def new(self, *args, **kws):
      print what
      return meth(self, *args, **kws)
    return new
  return what_sayer
Python 相关文章推荐
使用Python的Django框架实现事务交易管理的教程
Apr 20 Python
Django的session中对于用户验证的支持
Jul 23 Python
Python3的urllib.parse常用函数小结(urlencode,quote,quote_plus,unquote,unquote_plus等)
Sep 18 Python
一个Python最简单的接口自动化框架
Jan 02 Python
Python3.5基础之变量、数据结构、条件和循环语句、break与continue语句实例详解
Apr 26 Python
Python二进制文件读取并转换为浮点数详解
Jun 25 Python
对python中UDP,socket的使用详解
Aug 22 Python
Python实现微信机器人的方法
Sep 06 Python
Python pip 安装与使用(安装、更新、删除)
Oct 06 Python
通过实例解析Python RPC实现原理及方法
Jul 07 Python
python实现自动清理重复文件
Aug 24 Python
利用Python+OpenCV三步去除水印
May 28 Python
在Python的setuptools框架下生成egg的教程
Apr 13 #Python
简单介绍Python中的RSS处理
Apr 13 #Python
Python2.x和3.x下maketrans与translate函数使用上的不同
Apr 13 #Python
使用Pyrex来扩展和加速Python程序的教程
Apr 13 #Python
在Python中使用itertools模块中的组合函数的教程
Apr 13 #Python
Python中用Spark模块的使用教程
Apr 13 #Python
简单理解Python中基于生成器的状态机
Apr 13 #Python
You might like
thinkPHP框架对接支付宝即时到账接口回调操作示例
2016/11/14 PHP
通过修改Laravel Auth使用salt和password进行认证用户详解
2017/08/17 PHP
PHP实现数组转JSon和JSon转数组的方法示例
2018/06/14 PHP
PHP使用PhpSpreadsheet操作Excel实例详解
2020/03/26 PHP
firefox下对ajax的onreadystatechange的支持情况分析
2009/12/14 Javascript
Json和Jsonp理论实例代码详解
2013/11/15 Javascript
jQuery过滤选择器用法分析
2015/02/10 Javascript
基于Bootstrap实现的下拉菜单手机端不能选择菜单项的原因附解决办法
2016/07/22 Javascript
AngularJS中$injector、$rootScope和$scope的概念和关联关系深入分析
2017/01/19 Javascript
JS对象是否拥有某属性如何判断
2017/02/03 Javascript
MUI实现上拉加载和下拉刷新效果
2017/06/30 Javascript
Node.js学习之地址解析模块URL的使用详解
2017/09/28 Javascript
Vue 组件封装 并使用 NPM 发布的教程
2018/09/30 Javascript
小程序实现订单倒计时功能
2019/04/23 Javascript
kafka调试中遇到Connection to node -1 could not be established. Broker may not be available.
2019/09/17 Javascript
vue 单页应用和多页应用的优劣
2020/10/22 Javascript
实例解析Python设计模式编程之桥接模式的运用
2016/03/02 Python
Win8下python3.5.1安装教程
2020/07/29 Python
Python面向对象类编写细节分析【类,方法,继承,超类,接口等】
2019/01/05 Python
Django之创建引擎索引报错及解决详解
2019/07/17 Python
Django项目主urls导入应用中views的红线问题解决
2019/08/10 Python
Pytorch 实现自定义参数层的例子
2019/08/17 Python
详解python中*号的用法
2019/10/21 Python
基于python traceback实现异常的获取与处理
2019/12/13 Python
Python字符串的修改方法实例
2019/12/19 Python
浅析Python3 pip换源问题
2020/01/06 Python
python os.listdir()乱码解决方案
2021/01/31 Python
法国太阳镜店:Sunglasses Shop
2016/08/27 全球购物
HearthSong官网:儿童户外玩具、儿童益智玩具
2017/10/16 全球购物
小学数学国培感言
2014/03/10 职场文书
大专生找工作自荐书
2014/06/10 职场文书
股东授权委托书范本
2014/09/13 职场文书
党员干部反四风民主生活会对照检查材料思想汇报
2014/10/12 职场文书
毕业生自荐信范文
2015/03/05 职场文书
儿子满月酒致辞
2015/07/29 职场文书
vue前端工程的搭建
2021/03/31 Vue.js