什么是Pythonic获取“源”的方法。什么时候调用一个函数?

时间:2015-11-20 12:56:05

标签: python

鉴于下面的示例,是否有一个更优雅的解决方案,而不是传递字符串以允许函数进行测试,反过来,运行所需的代码?

myfunction(self, "location1")

def myfunction(self, source):
    if source == "location1":
        qs = MyModel.objects.filter(id = self.object.id)
        return qs
    elif source == "location2":
        qs = AnotherModel.objects.filter(id = self.object.id)
        return qs
    else:
        qs = YetAnotherModel.objects.filter(id = self.object.id)
        return qs

此示例包含虚拟Django查询,但我必须在整个项目中对各种Python函数使用此解决方案。

2 个答案:

答案 0 :(得分:2)

我认为这种方式更清晰:

def myfunction(self, source):
    models = { "location1": MyModel,
               "location2": AnotherModel,
               "location3": YetAnotherModel
             }
    selected = models.get(source, YetAnotherModel)
    qs = selected.objects.filter(id = self.object.id)
    return qs

答案 1 :(得分:0)

我认为这个可能没问题:

from collections import defaultdict
def myfunction(source):
    return defaultdict(lambda: YetAnotherModel.objects.filter(id = self.object.id),
           { "location1": MyModel.objects.filter(id = self.object.id),
             "location2": AnotherModel.objects.filter(id = self.object.id) })
           [source]

希望这有帮助!