Can a decorator of an instance method access the class?

后端 未结 13 956
没有蜡笔的小新
没有蜡笔的小新 2020-11-27 12:33

I have something roughly like the following. Basically I need to access the class of an instance method from a decorator used upon the instance method in its definition.

13条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-27 13:10

    This is an old question but came across venusian. http://venusian.readthedocs.org/en/latest/

    It seems to have the ability to decorate methods and give you access to both the class and the method while doing so. Note tht calling setattr(ob, wrapped.__name__, decorated) is not the typical way of using venusian and somewhat defeats the purpose.

    Either way... the example below is complete and should run.

    import sys
    from functools import wraps
    import venusian
    
    def logged(wrapped):
        def callback(scanner, name, ob):
            @wraps(wrapped)
            def decorated(self, *args, **kwargs):
                print 'you called method', wrapped.__name__, 'on class', ob.__name__
                return wrapped(self, *args, **kwargs)
            print 'decorating', '%s.%s' % (ob.__name__, wrapped.__name__)
            setattr(ob, wrapped.__name__, decorated)
        venusian.attach(wrapped, callback)
        return wrapped
    
    class Foo(object):
        @logged
        def bar(self):
            print 'bar'
    
    scanner = venusian.Scanner()
    scanner.scan(sys.modules[__name__])
    
    if __name__ == '__main__':
        t = Foo()
        t.bar()
    

提交回复
热议问题