建立一个函数调用? [英] Building a function call?
问题描述
有一个字符串:dothat
和一个元组:(x,y)
1.构建函数调用的最佳方法是什么:dothat(x,y)?
假设dothat在同一个模块中被定义,
2.是:eval(" dothat(x,y)",None,((''x'',100),(''y'',200)))
执行它的正确方法是什么?
如果在另一个模块中确定了dothat:
3.什么是正确的初始化全局变量以传递给eval的方法?
TIA,
Francois
Francois De Serres写道:Hiho,
有一个字符串:dothat
和一个元组:(x,y)
1。构建函数调用的最佳方法是什么:dothat(x,y)?
不是最好的(根本不是)但只有一种方式:
def dothat(x,y):
print" Called with:",x,y
c =(1,2)
locals()。get(" dothat")(* c)
----
被叫:1 2
HtH,Roland
Roland Heiber写道:不是最好的(根本不是)但只有一种方式:
def dothat(x,y):
print"调用:",x,y
c =(1,2)
locals()。get(" dothat")(* c)
正如你所说,不是最好的,但事实上在任何
情况下都不是真的可取。 locals()返回模块级别只有在执行时才会有东西
_at_模块级别(即不在函数内)。否则它将只返回它所在框架的局部变量。
这是更好的,因为它适用于OP的要求
情况。
globals()[''dothat''](* c)
-Peter
Roland Heiber写道:
Francois De Serres写道:
Hiho,
有一个字符串:dothat
和一个元组:(x,y)
1。构建函数调用的最佳方法是什么:dothat(x,y)?
不是最好的(根本不是)但只有一种方式:
还是很有意思,thx。
def dothat(x,y):
print" Called with:",x,y
< br => c =(1,2)
locals()。get(" dothat")(* c)
----
被叫搭配:1 2
HtH,Roland
Hiho,
Having a string: "dothat"
and a tuple: (x, y)
1. What''s the best way to build a function call like: dothat(x,y)?
Assuming dothat is def''d in the same module,
2. is: eval("dothat(x,y)", None, ((''x'', 100), (''y'', 200)))
the right way to have it executed?
If dothat is def''d in another module:
3. what would be the right way to initialize the globals to pass to eval ?
TIA,
Francois
Francois De Serres wrote:Hiho,
Having a string: "dothat"
and a tuple: (x, y)
1. What''s the best way to build a function call like: dothat(x,y)?
Not the best (not at all) but one way:
def dothat(x,y):
print "Called with:", x, y
c = (1,2)
locals().get("dothat")(*c)
----
Called with: 1 2
HtH, Roland
Roland Heiber wrote:Not the best (not at all) but one way:
def dothat(x,y):
print "Called with:", x, y
c = (1,2)
locals().get("dothat")(*c)
As you say, not the best, but in fact not really advisable under any
circumstances. locals() returns "module level" stuff only when executed
_at_ module level (i.e. not inside a function). Otherwise it will
return only the local variables of the frame its in.
Better is this, since it works for the OP''s requirements in either
situation.
globals()[''dothat''](*c)
-Peter
Roland Heiber wrote:
Francois De Serres wrote:Hiho,
Having a string: "dothat"
and a tuple: (x, y)
1. What''s the best way to build a function call like: dothat(x,y)?
Not the best (not at all) but one way:
Still pretty interesting, thx.
def dothat(x,y):
print "Called with:", x, y
c = (1,2)
locals().get("dothat")(*c)
----
Called with: 1 2
HtH, Roland
这篇关于建立一个函数调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!