I have a class, say, MyClass . I want to make a decorator for a method of this class (and some others). In the decorator, I would like to have a link to an object of this class.
Python 2 had a great inspect.getargspec function, which is now (in Pyton 3 ) deprecated .
Having stuck in the documentation, I found only a way to find out whether the self argument is in a function or not.
Here is an example of such a search:
import inspect def get_reference_by_method(f): all_args_of_method = inspect.signature(f).parameters if 'self' in all_args_of_method: print("I've found self!") else: raise Exception('It is not a class method') return None # I don't know how to get a reference on self def super_decorator(f): def wrapper(*args, **kwargs): self = get_reference_by_method(f) return f(*args, **kwargs) return wrapper class MyClass: @super_decorator def decorating_method(self): print('Hello from the decorating method') MyClass().decorating_method() Output to console:
I've found self! Hello from the decorated method I can not understand what I need to do to get this self .
def foo(bar, baz, self=None)also a completely valid class method, and an object of this class will be passed tobar- andreymanselfeverywhere. But are there any more correct alternatives? I can't find anything like that yet. - faoxis