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


Groups > comp.lang.python > #59802 > unrolled thread

Re: Fire Method by predefined string!

Started byIan Kelly <ian.g.kelly@gmail.com>
First post2013-11-17 15:09 -0700
Last post2013-11-17 15:09 -0700
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

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

#59802 — Re: Fire Method by predefined string!

FromIan Kelly <ian.g.kelly@gmail.com>
Date2013-11-17 15:09 -0700
SubjectRe: Fire Method by predefined string!
Message-ID<mailman.2808.1384726191.18130.python-list@python.org>
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.

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web