Skip to content Skip to sidebar Skip to footer

How To Make Every Class Method Call A Specified Method Before Execution?

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.

Solution 1:

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:

defadd_method_call(func, method_name):
    defreplacement(self, *args, **kw):
        getattr(self, method_name)()
        return func(self, *args, **kw)
    return replacement

defchange_all_attrs(cls, added_method):
    for method_name indir(cls):
        attr = getattr(cls, method_name)
        ifcallable(attr):
            setattr(cls, method_name, add_method_call(attr, added_method))

classanimals(object):
    ...

change_all_attrs(animals, '_internalMethod')

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 simple callable(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_attrs after creating the class, but the effect is the same (except you'll have to rewrite change_all_attrs to make it a decorator).

Post a Comment for "How To Make Every Class Method Call A Specified Method Before Execution?"