Python 什么';这是获得';来源';何时调用函数?
给出下面的示例,有没有比传递字符串更优雅的解决方案来允许函数测试,然后运行所需的代码Python 什么';这是获得';来源';何时调用函数?,python,Python,给出下面的示例,有没有比传递字符串更优雅的解决方案来允许函数测试,然后运行所需的代码 myfunction(self, "location1") def myfunction(self, source): if source == "location1": qs = MyModel.objects.filter(id = self.object.id) return qs elif source == "location2": q
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函数上使用此解决方案。我认为这种方法更简洁:
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
我想这个可能还可以:
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]
希望这有帮助 为什么不创建三个单独的函数并在每个位置调用它们呢?或者(如果您真的想要一个函数)-传递实际需要的对象,在这种情况下,
MyModel
,AnotherModel
或YetAnotherModel
。您可能想要这个或多个函数听起来不错。也许我是想太干了。谢谢你的评论。可能的副本还不错。但是“location4”
,因为输入将以键错误
异常中断此函数。@dopstar:你是对的!我忘记了默认情况,但我编辑了处理其他情况的代码;)这根本不是肾盂。我正在努力弄清楚它在做什么。@dopstar它只是一个带有默认值的字典。它的键是字符串,它的值只是函数。理解代码并不难。当然,你理解它是因为你做到了。这可能是因为代码表面看起来太多了。进口使它似乎没有优雅的方式做没有它,lambda增加了更多的燃料火。然后你也有了正常的dict,然后等待,这是一个笨拙的[源代码]
。这也是低效的,因为你实际上调用了所有的模型,这一点都不理想。对于每个“源”,您将调用所有模型。若他们正在通过API请求更改某些内容,那个么这将非常缓慢,而且可能也是一件危险的事情。