Python 类的装饰器

基于类的装饰器,思路跟基于函数的装饰器类似,但是需要注意类中的 getattr return

 

下面看一个示例:

 

def authentication(func):

    class Auth(object):

        def __init__(self, *args, **kwargs):
            print("Pre-Authentication")
            self.func = func(*args, **kwargs)
            print("Post-Authentication")

        def __getattr__(self, item):
            return getattr(self.func, item)

    return Auth


@authentication
class A(object):
    """
    测试类 A,用于各种类的功能测试。
    """

    def __init__(self, name):
        print("I Init: " + name)
        self.name = name

    def say(self):
        print("I Love: " + self.name)


if __name__ == '__main__':
    a = A("Python")
    a.say()


>> 执行结果

  Pre-Authentication
  I Init: Python
  Post-Authentication
  I Love: Python

 

 

 

 

本文章参考了ggGavin的 编写类装饰器

未完待续......

posted @ 2017-02-20 18:03  Vincen_shen  阅读(262)  评论(0编辑  收藏  举报