dynamic construction of variables / function names

limodou limodou at gmail.com
Thu Mar 30 09:00:37 CEST 2006


On 29 Mar 2006 22:44:24 -0800, Sakcee <sakcee at gmail.com> wrote:
> python provides a great way of dynamically creating fuctions calls and
> class names from string
>
> a function/class name can be stored as string and called/initilzed
>
> e.g
>
> def foo(a,b):
>     return a+b
>
> def blah(c,d):
>     return c*d
>
>
> list = ["foo", "blah"]
>
> for func in list:
>         print func(2,4)
>
> or similar items
>
>
> what is the way if the names of functions are some modification e.g
>
> def Newfoo(a,b):
>     return a+b
>
> def Newblah(c,d):
>     return c*d
>
> list = ["foo", "blah"]
>
> for func in list:
>         print "New"+func(2,4)
>
> or define a variable
>
> "New"+list[0] = "First Funciton"
>
>
> I think ,       print "New"+func(2,4)  and "New"+list[0] = "First
> Funciton"
>
> will not work,  either eval or exec should be used
> is it correct way, is there a simple way, is this techniqe has a name?
>
> thanks
>

You could get the function object from globals(), for example:

for func in list:
       f = globals().get("New"+func, None)
       if f and callable(f):
            print f(2, 4)

--
I like python!
My Blog: http://www.donews.net/limodou
My Site: http://www.djangocn.org
NewEdit Maillist: http://groups.google.com/group/NewEdit



More information about the Python-list mailing list