我目前正在尝试创建一个automagic django模型实例化器。这个函数需要几个参数,实例化几个django模型,将一些外键链接在一起,保存批次并将主模型返回给我。这一切都很好,但最后,该函数需要4个正常参数和2个元组(用不同的函数调用填充一个contenttype名称和一个参数数组)。是否可以减少样板函数中的参数数量?
这导致了下面的函数DEF:
def create_rule(profile, lifestyles, bool, title, input, output):
rule = Rule.objects.create(
user_profile=profile,
lifestyles=lifestyles,
bool=bool,
title=title,
)
models = ContentType.objects.filter(app_label="rules")
input_cls = models.get(model=input[0]).model_class()
input_cls.objects.create(*input[1], rule=rule)
output_cls = models.get(model=output[0]).model_class()
output_cls.objects.create(*output[1], rule=rule)
return rule
平均函数调用可能看起来有点像这样的东西:
create_rule(profile, '1,3,6,7', 1, "Switch off when 5:00",
('eventruleinput', [5, 'start']),
('propruleoutput', [35, 'Switch', 0]))
是否有减少的参数量的好方法我(我真的不知道)?有没有更好的方法来构造这个函数调用?我这样做是完全错误的吗?
注意:这只是一个模型实现,林有点想知道我想解决这个问题。
如果它是一个自动化从配置文件接收参数的一段代码然后它不是一个问题,但如果它是程序员必须编写这些参数,那么它可能是一个“优雅”,不正确的问题(恕我直言)。我不知道蟒蛇很抱歉,如果我在这里超过我的头。 – 2011-01-26 09:51:25