I want to make my Python Class behave in such a way that when any Class method is called a default method is executed first without explicitly specifying this in the called Class. An example may help 🙂
Class animals:
def _internalMethod():
self.respires = True
def cat():
self._internalMethod()
self.name = 'cat'
def dog():
self._internalMethod()
self.name = 'dog'
I want _internalMethod() to be called automatically when any method is called from an instance of animals, rather than stating it explicitly in the def of each method. Is there an elegant way to do this?
Cheers,
You could use a metaclass and getattribute to decorate all methods dynamically (if you are using Python 2, be sure to subclass from
object!).Another option is just to have a fixup on the class, like:
This is kind of sloppy,
dir()won’t get any methods in superclasses, and you might catch properties and other objects you don’t intend to due to the simplecallable(attr)test. But it might work fine for you.If using Python 2.7+ you can use a class decorator instead of calling
change_all_attrsafter creating the class, but the effect is the same (except you’ll have to rewritechange_all_attrsto make it a decorator).