Fire Method by predefined string!
Ian Kelly
ian.g.kelly at gmail.com
Sun Nov 17 17:09:05 EST 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 ???!
>
>
>
> Tamer
>
>
> class(object):
> def Fire(self,param)
> #possible ?!
> self.__param():
>
>
> 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:
class Spam(object):
def fire(self, name):
method = getattr(self, name)
method()
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
mailing list