python - 如何从列表中随机调用任何方法

标签 python web2py-modules

我对 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/

相关文章:

python - 如何将我的输出按列保存到 csv

MySQL 与 web2py : foreign key constraint failing

python - 如何在 Google App Engine (GAE) 上运行的 Web2py 上创建新的 auth_user 和 auth_group?

python - 在无限循环期间更新 Python 中的参数

python - Django simple_tag 和设置上下文变量

Python 多处理内置.IOError : [Errno 22] Invalid argument

python - 在 web.py 中获取自定义 HTTP 请求 header ?

python - 在 web2py Controller 中使用参数重定向 URL

web2py 组件

css - 如何在 web2py 中编辑 CSS 文件