Python dynamically add decorator to class' methods by decorating class

后端 未结 2 1270
谎友^
谎友^ 2020-12-13 22:11

say I have a class:

class x:

    def first_x_method(self):
        print \'doing first_x_method stuff...\'

    def second_x_method(self):
        print \'d         


        
2条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-13 22:54

    Here's a version of the trace decorator implemented as a class which allows for the other use case asked for: passing in the function to decorate all member functions of the decorated class with.

    import inspect
    
    
    def log(func):
        def wrapped(*args, **kwargs):
            try:
                print "Entering: [%s] with parameters %s" % (func.__name__, args)
                try:
                    return func(*args, **kwargs)
                except Exception, e:
                    print 'Exception in %s : %s' % (func.__name__, e)
            finally:
                print "Exiting: [%s]" % func.__name__
        return wrapped
    
    
    class trace(object):
    
        def __init__(self, f):
            self.f = f
    
        def __call__(self, cls):
            for name, m in inspect.getmembers(cls, inspect.ismethod):
                setattr(cls, name, self.f(m))
            return cls
    
    
    @trace(log)
    class X(object):
    
        def first_x_method(self):
            print 'doing first_x_method stuff...'
    
        def second_x_method(self):
            print 'doing second_x_method stuff...'
    
    x = X()
    x.first_x_method()
    x.second_x_method()
    

提交回复
热议问题