Dynamic call method in Python 2.7 using method name strings

I have a tuple that lists class methods, for example:

t = ('methA','methB','methC','methD','methE','methF') 

etc.

Now I need to dynamically call these methods based on user selection. Methods must be called based on the index. Therefore, if the user selects "0", methA is methA , if "5" is methF , methF .

My method for this is as follows:

 def makeSelection(self, selected): #methodname = t[selected] #but as this is from within the class , it has to be appended with 'self.'methodname # also need to pass some arguments locally calculated here 

I managed to work out something using eval , but it gives an error and is not at all elegant.

+13
python
source share
1 answer

If you call an object method (including imported modules), you can use:

 getattr(obj, method_name)(*args) # for this question: use t[i], not method_name 

eg:

 >>> s = 'hello' >>> getattr(s, 'replace')('l', 'y') 'heyyo' 

If you need to call a function in the current module

 getattr(sys.modules[__name__], method_name)(*args) 

where args is the list or tuple of arguments to send, or you can simply list them in a call, like any other function. Since you are in a method trying to call another method for the same object, use the first with self instead of obj

getattr takes an object and a string and searches for an attribute in the object, returning the attribute if it exists. obj.x and getattr(obj, 'x') achieve the same result. There are also functions setattr , hasattr and delattr if you want to learn more about this type of reflection.



A completely alternative approach:
Having noticed the amount of attention this answer received, I am going to suggest a different approach to what you are doing. I assume some methods exist

 def methA(*args): print 'hello from methA' def methB(*args): print 'bonjour de methB' def methC(*args): print 'hola de methC' 

So that each method corresponds to a number (highlighting), I build a dictionary that displays numbers in the methods themselves

 id_to_method = { 0: methA, 1: methB, 2: methC, } 

Given this, id_to_method[0]() will call methA . It consists of two parts: first id_to_method[0] , which gets the function object from the dictionary, then () calls it. I could also pass the argument id_to_method[0]("whatever", "args", "I", "want) In your real code, given the above, you would probably have something like

 choice = int(raw_input('Please make a selection')) id_to_method[choice](arg1, arg2, arg3) # or maybe no arguments, whatever you want 
+30
source share

All Articles