我有一个小数学实践应用程序,在其中,为了添加新问题,我只是定义一个新函数,它返回一些这样的字典:
def p4():
vertices = random.randrange(1, 8)
num_trees = random.randrange(2, 4)
format_dict = {
'vertices': vertices,
'num_trees': num_trees
}
answer_dict = {
'answer': vertices*num_trees,
'wrong_1': 0,
'wrong_2': 1,
'wrong_3': 'There do not exist any'
}
return {'question': format_dict, 'answers': answer_dict}
仅就某些情况而言,这是一个Django应用程序.其中每个问题的文本存储在模型中,并且当用户在网页上查看问题时,模型的文本根据format_dict格式化,并且根据answer_dict生成多项选择答案.
现在,上面定义的每个问题都有行返回{‘question’:format_dict,’answer’:answer_dict}.有没有办法可以用这两个字典调用这样的函数,并且在省略返回时具有相同的功能?我觉得好像 – 如果每个功能都需要有那条线 – 那么我可以做些什么来概括它(……装饰师,也许?我从未使用过一个,但现在可能是一个很好的借口).
处理字典的模型方法如下所示:
def gen_QAPair(self):
# The name/location of the problem's function is stored in 'module'
module = importlib.import_module(self.QAModule)
# This calls the function (p4, for example) and gets the dictionaries
qaPair = getattr(module, self.QAFunction)()
# This takes the unformatted text and formats it according to
# the returned format dictionary
formatted_text = self.unformatted_text.format(**qaPair['question'])
return {'question': formatted_text, 'answers': qaPair['answers']}
我唯一能想到的是将answer_dict和format_dict组合成一个字典字典,并返回它 – 但它不会真正保存很多代码,它只是在return语句之外定义键.
最佳答案 我看到两个选择.
首先,您想要概括所有问题函数都返回{‘question’形式的东西:format_dict,’answer’:answer_dict}.您可以将其表示为namedtuple
,或者如果您使用的是Python 3.7,则为data class.
命名元组示例:
from collections import namedtuple
ProblemData = namedtuple('ProblemData', ['question', 'answer'])
def q_n():
# ...
return ProblemData(format_dict, answer_dict)
这解决了一些概括结构的问题,但你仍然有回报.
更通用和更困难的方法是将每个问题存储在配置文件中.当然,您必须编写一些小语言和解析器来获得您想要的动态数据类型,但我想如果您扩展到数千个问题,那么值得付出努力.