Writing a class decorator that applies a decorator to all methods

后端 未结 3 1751
情歌与酒
情歌与酒 2020-12-13 16:26

I\'m trying to write a class decorator that applies a decorator to all the class\' methods:

import inspect


def decorate_func(func):
    def wrapper(*args,          


        
3条回答
  •  抹茶落季
    2020-12-13 16:47

    (Too long for a comment)

    I took the liberty of adding the ability to specify which methods should get decorated to your solution:

    def class_decorator(*method_names):
    
        def wrapper(cls):
    
            for name, meth in inspect.getmembers(cls):
                if name in method_names or len(method_names) == 0:
                    if inspect.ismethod(meth):
                        if inspect.isclass(meth.im_self):
                            # meth is a classmethod
                            setattr(cls, name, VerifyTokenMethod(meth))
                        else:
                            # meth is a regular method
                            setattr(cls, name, VerifyTokenMethod(meth))
                    elif inspect.isfunction(meth):
                        # meth is a staticmethod
                        setattr(cls, name, VerifyTokenMethod(meth))
    
            return cls
    
        return wrapper
    

    Usage:

    @class_decorator('some_method')
    class Foo(object):
    
        def some_method(self):
            print 'I am decorated'
    
        def another_method(self):
            print 'I am NOT decorated'
    

提交回复
热议问题