用类方法作为装饰器装饰同属于本类的另一个方法

#!/usr/bin/env python3
# -*- coding:utf-8 -*-

from operator import methodcaller


# 装饰类方法的装饰器,并可以通过传递类方法.功能:在被修饰的方法之前调用新增方法!
def doBefore(funName):
    def wrapper(fun):
        def inner(*args, **kwargs):
            cls = args[0]
            methodcaller(funName)(cls)
            return fun(*args, **kwargs)
        return inner
    return wrapper


class A():
    @doBefore(funName='bb')
    @doBefore(funName='cc')
    def aa(self, x, y):
        c = x + y
        print('{}+{}={}'.format(x, y, c))

    def bb(self):
        print('do other something!')

    def cc(self):
        print('do other something slse!')


if __name__ == '__main__':
    a = A()
    a.aa(3, 5)
原文地址:https://www.cnblogs.com/lxfdf/p/13731270.html