python - 随机选择功能

标签 python function variables random

我正在编写一个测试脚本,其中包含用于不同测试的不同函数。我希望能够随机选择一个测试来运行。我已经通过以下功能实现了这一点......

test_options = ("AOI", "RMODE")

def random_test(test_options, control_obj):
  ran_test_opt = choice(test_options)

  if ran_test_opt.upper() == "AOI":
     logging.debug("Random AOI Test selected")
     random_aoi()
  elif ran_test_opt.upper() == "RMODE":
    logging.debug("Random Read Mode Test selected")
    random_read_mode(control_obj)

但是,我想在不修改随机测试选择功能的情况下添加更多测试功能。我想做的就是将测试函数添加到脚本中。此外,我还想要一种方法来选择将包含在随机选择中的测试。这就是变量 test_options 所做的。我将如何改变我的随机生成函数来实现这一点?

编辑:我通过将所有测试都包含在测试类中来解决所有测试可能需要不同参数的事实。所有参数都将传递到 init 中,测试函数将使用“self”引用它们。当他们需要特定变量时...

class Test(object):
  """A class that contains and keeps track of the tests and the different modes"""

  def __init__(self, parser, control_obj):
    self.parser = parser
    self.control_obj = control_obj

  def random_test(self):
    test_options = []
    for name in self.parser.options('Test_Selection'):
        if self.parser.getboolean('Test_Selection', name):
            test_options.append(name.lower())

    ran_test_opt = choice(test_options)
    ran_test_func = getattr(self, ran_test_opt)
    ran_test_func()

  #### TESTS ####
  def random_aoi(self):
    logging.info("Random AOI Test")
    self.control_obj.random_readout_size()

  def random_read_mode(self):
    logging.info("Random Readout Mode Test")
    self.control_obj.random_read_mode()

最佳答案

您可以在 python 中创建一个您可以调用的函数列表:

test_options = (random_aoi, random_read_mode)

def random_test(test_options, control_obj):
    ran_test_opt = choice(test_options)
    ran_test_opt(control_obj) # call the randomly selected function

你必须让每个函数以这种方式接受相同的参数,这样你才能以相同的方式调用它们。

关于python - 随机选择功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22016917/

相关文章:

python - Spark 中可能彼此略有不同的日志行的正则表达式

强制转换为指向函数返回数组的指针 - 允许吗?

function - 我用 go 编写的递归函数有什么问题?

c++ - 如何将函数指针作为模板参数传递

php - 未解析基本语法的解决方法

java - 泛型类型类定义

python - 为什么python round(np.float16(np.pi),5) 返回无穷大?错误、限制或预期?

python - Grep for multiple strings 和多个字符串包括以下行

javascript - 如何获取用户的输入并将其存储以用于 Javascript 函数?

python - 如何使用 Python (scikit-learn) 计算 FactorAnalysis 分数?