Fire Method by predefined string!

Roy Smith roy at panix.com
Sun Nov 17 17:20:52 EST 2013


In article <mailman.2807.1384725251.18130.python-list at python.org>,
 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!'

I'm not sure why you'd want to do this, but it's certainly possible (as, 
I imagine it would be, in any language that has introspection).  You can 
use getattr() to look up an attribute by name.  Here's a little program 
which demonstrates this:

class C:
    def Fire(self, param):
        print "I'm Fire"
        try:
            f = getattr(self, param)
            f()
        except AttributeError as ex:
            print "==> %s" % ex

    def _DoSomething(self):
        print "I'm _DoSomething"

if __name__ == '__main__':
    c = C()
    c.Fire("_DoSomething")
    c.Fire("blah")



$ python s.py
I'm Fire
I'm _DoSomething
I'm Fire
==> C instance has no attribute 'blah'

One thing to be aware of is that a single underscore in front of a name 
is fine, but a double underscore (i.e. "__DoSomething") invokes a little 
bit of Python Magic and will give you unexpected results.



More information about the Python-list mailing list