Fire Method by predefined string!
ian.g.kelly at gmail.com
Sun Nov 17 23:09:05 CET 2013
On Sun, Nov 17, 2013 at 2:46 PM, Tamer Higazi <th982a at googlemail.com> wrote:
> Hi people!
> Assume we have 2 methods, one called Fire and the other __DoSomething.
> I want the param which is a string to be converted, that I can fire
> directly a method. Is it somehow possible in python, instead of writing
> if else statements ???!
> def Fire(self,param)
> #possible ?!
> def _DoSomething(self):
> print 'I did it!'
You can use the getattr function to resolve an attribute (such as a
method) on an object by name. For example:
def fire(self, name):
method = getattr(self, name)
Note that if the parameter is derived from untrusted user input, this
can be a potential security hole, as the user can potentially name
*any* attribute of the object.
More information about the Python-list