How to intercept instance method calls?

后端 未结 3 1779
孤街浪徒
孤街浪徒 2020-12-08 11:47

I am looking for a way to intercept instance method calls in class MyWrapper below:

class SomeClass1:
    def a1(self):
        self.internal_z         


        
3条回答
  •  暖寄归人
    2020-12-08 12:35

    What you want to do is quite similar to this question. You should take your example code in the reverse order, i mean creating a class to record return values of method calls, and make the classes you want to watch inherit from it. Which would give something like this

    class RetValWatcher(object):
        def __init__(self):
            self.retvals = []
    
        def __getattribute__(self, name):
            attr = super(RetValWatcher, self).__getattribute__(name)
            if callable(attr):
                def wrapped(*args, **kwargs):
                    retval = attr(*args, **kwargs)
                    self.retvals.append(retval)
                    return retval
                return wrapped
            else:
                return attr
    
        def getFinalRestult(self):
            return ''.join(self.retvals)
    
    class MyClass(RetValWatcher):
        def a(self):
            self.internal_z()
            return 'a1'
    
        def b(self):
            return 'b1'
    
        def internal_z(self):
            return 'z'
    
    x = MyClass()
    x.a()
    x.b()
    print x.getFinalResult()
    #'za1b1'
    

    With some minor changes, this method would also allow you to record return values across all RetValWatcher instances.

    Edit: added changes suggested by singularity's comment

    Edit2: forgot to handle the case where attr is not a method (thx singularity again)

提交回复
热议问题