late bindings ???
Alfredo P. Ricafort
alpot at mylinuxsite.com
Tue Dec 3 03:03:47 EST 2002
Hi,
First of all, thank you for all your suggestions.
I can pretty much sum up my options into 2:
Option 1: using globals/eval
============================
def f2(arg):
print 'arg=',arg
class c:
def f1(self):
f='f2'
globals()[f]('globals')
eval(f)('eval')
x=c()
x.f1()
Option 2: using getattr
=======================
class c:
def f1(self):
f='f2'
x=getattr(self,f)
x('getattr')
def f2(self,arg):
print 'arg=',arg
x=c()
x.f1()
Option 1 seems to have a limitation that you cannot call functions in
a class ??? On the other hand, option 2 can only call functions in a
class ???
AL
On Mon, 2002-12-02 at 22:40, Gonçalo Rodrigues wrote:
> On 02 Dec 2002 21:22:38 +0800, "Alfredo P. Ricafort"
> <alpot at mylinuxsite.com> wrote:
>
> >Hi,
> >
> >I'm trying to create a flexible python program where the called
> >functions are stored in a list. But before you can assign the function
> >name in a list, it must be in the namespace. However, in my case, the
> >function names are known later. So what I did was to store it as a
> >string instead and do something like this:
> >
> >func=['do_file','do_exit']
> >apply(func[i],[args])
>
> What did you expect this to do? You get a string (func[i]) and then try
> to apply it to some args and... you get an exception.
>
> Functions (as pretty much everything else) are first-class objects in
> Python. This means that:
>
> - They can be assigned to variables
> - They can be passed as arguments to other functions
> - They can be returned as function arguments
>
> >
> >But this doesn't work!
>
> I do not understand exactly what you want, but maybe the next snippet
> will help you
>
> >>> def test():
> ... print "A test!"
> ...
> >>> #A dictionary of functions.
> >>> funcdict = {}
> >>> funcdict['myfunc'] = test
> >>> funcdict['myfunc']()
> A test!
>
> HTH,
> G. Rodrigues
More information about the Python-list
mailing list