当前位置: 动力学知识库 > 问答 > 编程问答 >

python - function definition in eval

问题描述:

I try to define a function with a variable name.

Names are retrieved from a database. For every name I want to define a button and have separate handling:

title=['BNL','CE']

for i in range(0,len(title)):

panelvpu.add(Button(title[i]))

for i in range(0,len(title)):

eval('def onButtonClick'+title[i]+'(self, event):')

eval(' Window.alert("Yes")')

The button definition is ok, but the handling of the event in the defined function gives an error

im1 SyntaxError: at index 4 in "def onMenu1Item1(self):

Window.alert("Item 1 selected")": expected ';', got 'onMenu1Item1'

After feedback I changed this to

 title=['BNL','CE']

for t in title : panelvpu.add(Button(t))

for t in title:

def_code = "print t"

exec(def_code)

Just to get the feeling; under python this works fine.

But I use pyjamas and the last code does rais the error stating

 im1 TypeError: iter is undefined

It appears that pyjamas is not supporting eval() and exec() yet.

Richard

网友答案:

There are a number of problems here:

1) eval is for evaluating an expression, not executing statements.

2) exec would need the entire function in one exec, not split onto separate lines as you have it.

3) There are much easier ways to create functions, depending on what you want to have in the body. Tell us about what you really want to do.

4) Your loop is much simpler as: for t in title: blah blah t.

分享给朋友:
您可能感兴趣的文章:
随机阅读: