Python装饰器与面向切面编程

1. 概述

装饰器是一个很著名的设计模式,经常被用于有切面需求的场景,较为经典的有插入日志、性能测试、事务处理等。装饰器是解决这类问题的绝佳设计,有了装饰器,我们就可以抽离出大量函数中与函数功能本身无关的雷同代码并继续重用。概括的讲,装饰器的作用就是为已经存在的对象添加额外的功能。
Python从语法层为我们提供了非常好的实现装饰模式的方法。

2. 动机

如果不使用python
装饰器语法的话,我们如果想转换一个函数(或换句话说,给函数加上装饰器,例如将一个普通函数转变成类函数)的话,代码看起来是这样子的:

'''
Created on 2011-12-14
 
@author: Ahan
'''
class Foo(object):
    def foo(self):
        print("foo is called")
        pass
    #Turn the method foo to a class method
    foo = classmethod(foo)
 
if __name__ == '__main__':
    Foo.foo()
    pass

可以想象,函数一多,代码的可读性就大大下降了。Python
提供了一个另一种优雅的方法来解决这个问题。修改后的代码如下:

'''
Created on 2011-12-14
 
@author: Ahan
'''
class Foo(object):
    #Turn the method foo to a class method
    @classmethod
    def foo(self):
        print("foo is called")
        pass
if __name__ == '__main__':
    Foo.foo()
    pass

代码量减少了,可读性也强了,函数的特性也很直观。

3. 当前语法

当前Python
的装饰器语法如下:

@dec2
@dec1
def func(arg1, arg2, ...):
pass

上面的代码相当于:

def func(arg1, arg2, ...):
    pass
func = dec2(dec1(func))
4. 装饰器的更多用法示例

我们可以使用Python
装饰器来更加直接了当地使用
staticmethod()

classmethod()
内置函数,但装饰器的作用远不止于此。

1.例如我们要定义一个函数,当程序退出的时候调用此函数。

def onexit(f):
    import atexit
    atexit.register(f)
    return f
 
@onexit
def func():
...

注意在真实场景中我们可能不会这么做,上面代码只是用作示例。
2.使用Python
装饰器实现单例模式。

def singleton(cls):
    instances = {}
    def getinstance():
        if cls not in instances:
            instances[cls] = cls()
        return instances[cls]
    return getinstance
 
@singleton
class MyClass:
    ...

3.给函数添加属性。

def attrs(**kwds):
    def decorate(f):
        for k in kwds:
            setattr(f, k, kwds[k])
        return f
    return decorate
 
@attrs(versionadded="2.2",
       author="Guido van Rossum")
def mymethod(f):
    ...

4.声明类实现了某些接口。

def provides(*interfaces):
     """
     An actual, working, implementation of provides for
     the current implementation of PyProtocols.  Not
     particularly important for the PEP text.
     """
     def provides(typ):
         declareImplementation(typ, instancesProvide=interfaces)
         return typ
     return provides
 
class IBar(Interface):
     """Declare something about IBar here"""
 
@provides(IBar)
class Foo(object):
        """Implement something here..."""

参考资料:http://www.python.org/dev/peps/pep-0318/#examples

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 136,230评论 19 139
  • # Python 资源大全中文版 我想很多程序员应该记得 GitHub 上有一个 Awesome - XXX 系列...
    aimaile阅读 26,773评论 6 427
  • “平地泉源觱沸三窟突起雪涛数尺,声如隐雷,冬夏如一” ——《历城县志》 传闻趵突泉,世人游而其见者,无不咄咄称奇,...
    信言不美阅读 3,244评论 0 2
  • 最近读了《深度工作》这本书,受益匪浅。这是本被《纽约时报》、《华尔街日报》力荐的畅销书,曾引发数百万讨论的年度话题...
    AI善待自己阅读 6,691评论 0 1
  • 晨起感恩 感恩父母生养之恩,供我读书,从小都没让我受过苦,长大后也是一直的为我着想,自己开店了,感恩父亲帮我做饭,...
    黄巧珍阅读 1,351评论 0 1

友情链接更多精彩内容