I want to set a class state variable before running any class methods every time I call a method; is there a way to use __getattribute__ to run a pre-command hook and continue on to the attr specified? Would I have to use a metaclass, for example?
>Solution :
To do this using __getattribute__ you could do something like this.
import inspect
class A:
def __getattribute__(self, attrname):
attr = super().__getattribute__(attrname)
if inspect.ismethod(attr):
# Do state stuff
return attr
Instead of using __getattribute__ you could also create a decorator function that does the state stuff you want to do, and add that to each method you want it to apply to.