1

我还是 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

在控制器中,我导入了如下方法,尽管方法比显示的要多得多

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,而不调用其他方法。当用户输入任何查询时,我想随机调用任何方法。

4

4 回答 4

2

你正在寻找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....
于 2014-07-10T16:28:44.963 回答
1

如果您想随机调用方法,请使用random.choice

def foo1():
    print "hello"

def foo2():
     print "world"

def foo3():
     print "goodbye"

def foo4():
     print "world"
GO = [foo1, foo2, foo3, foo4]

import random

def Foo():
    func = random.choice(GO)
    return func()
In [30]: Foo()
world

In [31]: Foo()
goodbye

In [32]: Foo()
hello

In [33]: Foo()
goodbye
于 2014-07-10T17:02:34.127 回答
1

只有 method1 被调用,因为你是从循环内部返回的,所以循环也退出了。你想返回什么?可能是所有返回值的列表?

def Foo():
    ret_list = []
    for (func) in G0:
        ret_list.append(func())
    return ret_list
于 2014-07-10T16:24:35.940 回答
0

您是否尝试在 中运行所有这些方法G0?如果是这样,问题是您正在使用return func(). return关键字一被调用就会退出,Foo()这就是为什么只调用一个函数的原因。如果您想存储该值,您应该只使用func()或。result = func()

如果您只想运行其中一种方法,则需要放弃for循环并使用return G0[x]()x您要调用的函数的列表索引在哪里。

于 2014-07-10T16:23:27.010 回答