Re: dynamic call of a function

From: kishore (prakis_at_gmail.com)
Date: 01/22/05


Date: 22 Jan 2005 03:40:57 -0800

Hi Luigi Ballabio,

Thankyou very much for your reply,
it worked well.

Kishore.

Luigi Ballabio wrote:
> At 10:37 AM 10/19/01 +0200, anthony harel wrote:
> >Is it possible to make dynamic call of a function whith python ?
> >
> >I have got a string that contains the name of the function I
> >want to call but I don't want to do something like this :
> >
> >if ch == "foo" :
> > self.foo( )
> >elif ch == "bar"
> > self.bar( )
> >....
>
> Anthony,
> here are two ways to do it---I don't know which is the best,
nor
> whether the best is yet another. Also, you might want to put in some
error
> checking.
>
> class Test:
> def foo(self):
> print 'Norm!'
> def bar(self):
> print 'Dum-de-dum'
> def dynCall1(self,methodName):
> eval('self.%s()' % methodName)
> def dynCall2(self,methodName):
> method = vars(self.__class__)[methodName]
> method(self)
>
> >>> t = Test()
> >>> t.dynCall1('foo')
> Norm!
> >>> t.dynCall2('bar')
> Dum-de-dum
>
> Bye,
> Luigi



Relevant Pages

  • Taint (like in Perl) as a Python module: taint.py
    ... The following is my first attempt at adding a taint feature to Python ... string to create a safe string from it. ... def replace: ...
    (comp.lang.python)
  • Memory Question
    ... I have wrote a helper to my program which monitors object count, memory utilization and a threshold of 10% to determine how many objects are sticking around and how many are being garbage collected. ... occured right before the original String count). ... def print_threshold_breakers hsh1, hsh2, threshold ... putsf 'Building mem usage', mem_usage ...
    (comp.lang.ruby)
  • Re: [QUIZ] Editing Text (#145)
    ... I start by partially implementing a string class that works equally ... a single "gap" and recirculates unused space better. ... def inspect ... # remove excess trailing space if too much ...
    (comp.lang.ruby)
  • Re: Named/positional method args
    ... duck-typing isn't going to do a bit of good ... if one of those is passed in instead of the String representation. ... def to_file; self end ... It's not really limiting to specify types in method interfaces. ...
    (comp.lang.ruby)
  • UnicodeEncodeError in Windows
    ... def getdamage: ... """reads each line of war report ... """Build a string from a warrior's stats ... As I understand it the error is related to the ascii codec being ...
    (comp.lang.python)