如何从lis中随机调用任何方法

2024-04-26 23:00:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我对web2py和python还是个新手,在我的web2py应用程序中,我创建了这个在pythonshell中运行良好的代码。你知道吗

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]处的method1,而不调用其他方法。当用户输入任何查询时,我想随机调用任何方法。你知道吗


Tags: 方法代码answerfromimportreturndef方式
3条回答

如果要随机调用方法,请使用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

只调用method1,因为您是从循环内部返回的,所以循环也会退出。你想退货什么?所有返回值的列表?你知道吗

def Foo():
    ret_list = []
    for (func) in G0:
        ret_list.append(func())
    return ret_list

你在找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....

相关问题 更多 >