Chinaunix

标题: Python的decorator方法 [打印本页]

作者: jupiters    时间: 2009-03-23 16:27
标题: Python的decorator方法

                和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
               
               
               
               
               

本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u/412/showart_1876311.html




欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2