Here's the code:
def method1(): print "This is method 1" def method2(): print "This is method 2" def method3(): print "This is method 3" def method4(): print "This is method 4" def noSuchMethod(): print "No such method" def methodChainerFunc(obj, listOfMethods): """Invokes all the methods provided to it in the list of methods If a method does not exist then calls the noSuchMethod""" for method in listOfMethods: getattr(obj,method,noSuchMethod)() if __name__ == "__main__": li = ["method1","method2"] methodChainerFunc(methodChainer,li)
Couple of interesting things I want to point out are:
1) The function list can be dynamic, so one can specify at the runtime the functions and order in which these functions should be executed though we can have certain tuples that can act as standard order in which the functions should be called. An interesting use case that I can think of is implementing the holder and decorator pattern like this.
2)Also currently the methods don't take any input, but these can be easily modified to take and return the same input so that it can be easily passed around methods with each method modifying it.
May be this whole idea is totally stupid, or may be s.th like this already exists, just thought of putting it out anyways.
No comments:
Post a Comment