Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #59802

Re: Fire Method by predefined string!

References <52893928.1010907@googlemail.com>
From Ian Kelly <ian.g.kelly@gmail.com>
Date 2013-11-17 15:09 -0700
Subject Re: Fire Method by predefined string!
Newsgroups comp.lang.python
Message-ID <mailman.2808.1384726191.18130.python-list@python.org> (permalink)

Show all headers | View raw


On Sun, Nov 17, 2013 at 2:46 PM, Tamer Higazi <th982a@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.

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

Re: Fire Method by predefined string! Ian Kelly <ian.g.kelly@gmail.com> - 2013-11-17 15:09 -0700

csiph-web