Python: Do something for any class method?

Say I have a class with a bunch of methods:

class Human(): def eat(): print("eating") def sleep(): print("sleeping") def throne(): print("on the throne") 

Then I run all the methods with

 John=Human() John.eat() John.sleep() John.throne() 

I want to run print("I am") for each method called. So I should get something like

 I am: eating I am: sleeping I am: on the throne 

Is there a way to do this without reformatting each method?

+5
source share
4 answers

If you cannot change the way you call your methods, you can use the __getattribute__ magic method (the methods are too remembered for attributes!), You just need to be careful to check the type of the attributes so that you don't type “I:” every time you want to get access to any sting or int attributes that may be present:

 import types class Human(object): def __getattribute__(self, attr): method = object.__getattribute__(self, attr) if not method: raise Exception("Method %s not implemented" % attr) if type(method) == types.MethodType: print "I am:" return method def eat(self): print "eating" def sleep(self): print "sleeping" def throne(self): print "on the throne" John = Human() John.eat() John.sleep() John.throne() 

Outputs:

 I am: eating I am: sleeping I am: on the throne 
+5
source

You can do this if you don't mind adding the __init__ and __call__ to your class and self to the method arguments.

 class Human(): def __init__(self): return None def __call__(self, act): print "I am:" method = getattr(self, act) if not method: raise Exception("Method %s not implemented" % method_name) method() def eat(self): print "eating" def sleep(self): print "sleeping" def throne(self): print "on the throne" John = Human() John("eat") John("sleep") John("throne") 

EDIT : see my other answer for a better solution

+2
source

If you also want to have arguments, you can try using metaprogramming to change the class methods yourself to perform the pre / post operation, for example, the answer to How to start a method before / after all calls to class functions with arguments passed?

0
source

You can write another method, for example def iam() , and write code in the print "i am \n" method print "i am \n" and call it before each method.

-3
source

Source: https://habr.com/ru/post/1203384/


All Articles