我对 web2py 和 python 还是新手,在我的 web2py 应用程序中,我创建了这段在 python shell 中运行良好的代码。
python 模块: 这些方法的工作方式是用户输入方程式查询以获得答案。如果它是一个加法,method1 会解决它,与调用其他方法相同以执行不同的代码,例如
def method1():# to do additions
name = input('Please Enter equation here: ').lower()
if '1 + 1':
answer = code
return answer
def method2():# to do subtractions
name = input('Please Enter equation here: ').lower()
if '1 - 1':
answer = code
return answer
在 Controller 中,我导入了如下方法,尽管方法比显示的要多得多
from applications ...... import method1
from applications ...... import method2
from applications ...... import method3
from applications ...... import method4
method1 = method1
method1 = method2
method1 = method3
method1 = method4
G0 = [method1, method2, method3, method4]
def Foo():
code..
for (func) in G0:
return func()
问题是只有位于列表中位置[0] 的方法1 被调用,而不是其他方法。我想在用户输入任何查询时随机调用任何方法。
最佳答案
您正在寻找yield
。
G0 = [method1, ..., method4]
def foo():
for method in G0:
yield method()
method_results = foo()
type(method_results) # <class 'generator'>
for result in method_results:
print(result)
## OUTPUT will be each result, one per line
虽然我认为更深层次的问题是:
method1 = method1
method1 = method2 # method1 = ... huh?
method1 = method3 # help I'm trapped in an
method1 = method4 # overwrite factory....
关于python - 如何从列表中随机调用任何方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24681649/