[英]Variable function call in Python
I'm designing a tool which recursively identifies upstream pathways in a vector river network. 我正在设计一种工具,该工具可以递归地识别向量河网中的上游路径。 I'd like to be able to truncate the search if the cumulative path cost passes a test which is defined by the user, and I'm not sure whether this is possible.
如果累积路径成本通过了用户定义的测试,我希望能够截断搜索,并且不确定是否可行。 Below is an example of the sort of thing I'd like to do:
以下是我想做的事情的一个示例:
def test1(value):
if value > 1: return True
else: return False
def test2(value):
if value % 4: return True
else: return False
def main(test):
for i in range(20):
if SPECIFIEDTEST(i):
print i
break
main(test1)
I know exec() can be used for this purpose but I also understand this is frowned upon? 我知道exec()可以用于此目的,但我也明白这很皱眉? Is there another, better method for passing a function to another function?
是否有另一个更好的方法将一个函数传递给另一个函数?
You can create a dictionary that maps function names to the actual functions, and use that: 您可以创建一个将函数名称映射到实际函数的字典,并使用该字典:
tests = {'test1': test1, 'test2': test2}
if tests[specifiedtest](i):
...
Building a dictionary for this is unnecessary, as functions can be passed in as parameters to other functions. 无需为此构建字典,因为可以将函数作为参数传递给其他函数。 Simply pass the function into
main()
只需将函数传递给
main()
def test1(value):
if value > 1: return True
else: return False
def test2(value):
if value % 4: return True
else: return False
# using test1 as the default input value...
def main(test = test1):
for i in range(20):
if test(i):
print i
break
main(test1)
# prints 2
main(test2)
# prints 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.