Home > Software design >  How to get an instance reference from inside a decorator of a method of this intance?
How to get an instance reference from inside a decorator of a method of this intance?

Time:08-18

I am trying to get the instance reference inside a decorator of a method. But the reference I am getting is not bound to an object. How to solve this problem?

class A:
   def f(self):
      pass

print(A().f.__self__) # prints the object reference <__main__.A object at 0x10ebfd7f0>

if we add a decorator it still works:

def decor(initial_method):
    def wrapped_method(*args, **kwargs):
           ....
        return ...
    return wrapped_method

class A:
    def f(self):
        pass
    @decor
    def f2(self):
        pass

print(A().f.__self__) # prints <__main__.A object at 0x10ebfd7f0>
print(A().f2.__self__) # prints <__main__.A object at 0x10ebfd7f0>

But If I try to get the instance from within the decorator I am receiving an error:

def decor(initial_method):
    def wrapped_method(*args, **kwargs):
        print(initial_method.__self__)
           ....
        return ...
    return wrapped_method

class A:
    def f(self):
        pass
    @decor
    def f2(self):
        pass

A().f2() # throws an error : AttributeError: 'function' object has no attribute '__self__'

The Problem is probably because the function "initial_method" is not bound at the moment of decoration. I can understand it. But is there any way of getting the instance inside the decorator?

CodePudding user response:

args[0] inside wrapped_method is an equivalent to self in a decorated function.

  • Related