How to dynamicly define function and call the function?

FAN sharprazor at gmail.com
Thu Sep 8 21:45:40 EDT 2005


I want to define some function in python script dynamicly and call
them later, but I get some problem. I have tried the following:

##################################
# code
##################################
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!

d = test()
d.show('hello')
###################################
#output 
##################################
exec def function
Msg in init ...
Traceback (most recent call last):
  File "test.py", line 10, in ?
    d.show('hello')
  File "test.py", line 7, in show
    dfunc(msg)
NameError: global name 'dfunc' is not defined
##################################

I think this maybe cause by the scope of function definition, for the
first call of 'dfunc' in __init__ work. So I tried to define the
function as a member function of class 'test', but this time even the
first call doesn't work:

##################################
# code
##################################
class test:
        def __init__(self):
            exec("def dfunc(self,msg):\n\tprint msg\nprint 'exec def function'")
            self.dfunc('Msg in init ...')
			
        def show(self, msg):
             exec("self.dfunc(msg)")

d = test()
d.show('hello')
###################################
#output 
##################################
exec def function
Traceback (most recent call last):
  File "test.py", line 9, in ?
    d = test()
  File "test.py", line 4, in __init__
    self.dfunc('Msg in init ...')
AttributeError: test instance has no attribute 'dfunc'
##################################

Is there any way I can solve this problem?

Regards

- FAN



More information about the Python-list mailing list