Can a decorator of an instance method access the class?

后端 未结 13 900
没有蜡笔的小新
没有蜡笔的小新 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:16

    You will have access to the class of the object on which the method is being called in the decorated method that your decorator should return. Like so:

    def decorator(method):
        # do something that requires view's class
        def decorated(self, *args, **kwargs):
            print 'My class is %s' % self.__class__
            method(self, *args, **kwargs)
        return decorated
    

    Using your ModelA class, here is what this does:

    >>> obj = ModelA()
    >>> obj.a_method()
    My class is <class '__main__.ModelA'>
    
    0 讨论(0)
提交回复
热议问题