How to dynamicly define function and call the function?

Leif K-Brooks eurleif at ecritters.biz
Fri Sep 9 05:53:00 CEST 2005


FAN wrote:
> class test:
>         def __init__(self):
>             exec("def dfunc(msg):\n\tprint msg\nprint 'exec def function'")
>             dfunc('Msg in init ...')   #  it work
> 			
>         def show(self, msg):
>              dfunc(msg) # doesn't work !
>              exec('dfunc(msg)')  # doesn't work too!

class Test(object):
    def __init__(self):
        exec "def dfunc(msg):\n print msg"
        dfunc('Hello from __init__.')
        self.dfunc = dfunc

    def show(self, msg):
        self.dfunc(msg)


(Of course, this is assuming your real function is more complicated than
the one you've posted; if it isn't, you don't need to use exec to define
it.)



More information about the Python-list mailing list