I know that you can't use an instance attribute as an argument in a method because the method's parameters are evaluated before the instance is created. But I am interested in doing something like the following.
class deco2:
def __init__(self, activation, nombre):
self.activation = activation
self.nombre = nombre
def __call__(self, func):
def wraped(*args, **kwargs):
print (f'{self.activation} {self.nombre}')
func(*args, **kwargs)
return wraped
class Base:
def __init__(self, nombre):
self.nombre = nombre
@deco2('update', self.nombre)
def update(self, arg):
print (f"{arg} desde método update")
b = Base('NombreInstancia')
b.update('prueba')
I have looked into the ´´´inspect´´´ module but I have not been able to find a way to know the name of a method instance. Another thing that would be interesting to know how it is done.
What solution would you give?
The most obvious solution would be instead of passing the attribute directly to the decorator (which isn't possible because the attribute doesn't exist until the initializer as you comment is executed), intercept it at runtime (when the call to occurs
__call__
) from of the decorated method, which always receives as its first argument the instance of the class to which it belongs, with which we can access the attribute in a simple way.To make the decorator more flexible, it can be passed the attribute name as a string and used
getatrr
to get it from the instance. This allows us to use the decorator with any instance attribute regardless of its name.A possible implementation of the idea:
Departure:
If you want to know the name of a model instance you can use
name = mymodel.__name__
or more specificname = instancia.__name__
, then you can use this variable as you wishFollowing FJSevilla's recommendation, I apply it as follows. But I get a new problem... I realize that I don't need to pass arguments to the decorator class and I get the information I need from the decorated function and the instance. But is it essential that the decorator have empty parentheses?
By removing the parentheses I see that the behavior of the decorator class changes. init receives as argument the function to decorate and call the arguments of the function. I try to access the instance of the Base class but what I try fails.
At the moment I am at the next point and I do not understand very well what is happening.