免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1873 | 回复: 0
打印 上一主题 下一主题

Python的decorator方法 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2009-03-23 16:27 |只看该作者 |倒序浏览

                和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
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP