Chinaunix首页 | 论坛 | 博客
  • 博客访问: 39887
  • 博文数量: 10
  • 博客积分: 1400
  • 博客等级: 上尉
  • 技术积分: 130
  • 用 户 组: 普通用户
  • 注册时间: 2009-03-18 22:21
文章分类

全部博文(10)

文章存档

2010年(1)

2009年(9)

我的朋友

分类: Python/Ruby

2009-03-23 16:27:04

和C++/Java里面的decorator功能相似,Python里面的decorator主要用于派生多个decorator对象在一个连续的流,每一个decorator都完成之前或之后的功能。
但是在Python里面,decorator功能的实现不是从decorator对象过来,而是从函数出发,这和Python2.2 引入的classmethod()和staticmethod()内置函数有关。

功能:
1. 对类的方法做一个修饰(可以在方法执行之前或之后).可用于python多线程的同步。
如下形式:
 >>> 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
...


2. 在类实例化的时候对类做一些修改,比如删除或添加一些方法。
如下例:
 def flaz(self): return 'flaz'     # Silly utility method
def flam(self): return 'flam'     # Another silly method

def change_methods(new):
    "Warning: Only decorate the __new__() method with this decorator"
    if new.__name__ != '__new__':
        return new  # Return an unchanged method
    def __new__(cls, *args, **kws):
        cls.flaz = flaz
        cls.flam = flam
        if hasattr(cls, 'say'): del cls.say
        return super(cls.__class__, cls).__new__(cls, *args, **kws)
    return __new__

class Foo(object):
    @change_methods
    def __new__(): pass
    def say(self): print "Hi me:", self

foo = Foo()
print foo.flaz()  # prints: flaz
foo.say()         # AttributeError: 'Foo' object has no attribute 'say'


详细内容:
http://www.ibm.com/developerworks/cn/linux/l-cpdecor.html
阅读(1310) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~