【问题标题】:How to randomly call any method from a list如何从列表中随机调用任何方法
【发布时间】:2014-07-10 16:21:29
【问题描述】:

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

【问题讨论】:

  • 是随机调用一个方法还是调用所有方法?

标签: python web2py-modules


【解决方案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....

【讨论】:

    【解决方案2】:

    如果你想随机调用方法使用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
    

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        【解决方案4】:

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

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2013-07-10
          • 1970-01-01
          • 2014-01-10
          • 2021-12-16
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-01-11
          相关资源
          最近更新 更多