【问题标题】:What's the Pythonic way to get the 'source' when a function is called?调用函数时获取“源”的 Pythonic 方法是什么?
【发布时间】:2015-11-20 12:56:04
【问题描述】:

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

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 函数上使用此解决方案。

【问题讨论】:

标签: python


【解决方案1】:

我认为这种方式更干净:

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

【讨论】:

  • 不错。但是"location4" 作为输入会破坏这个函数,并出现KeyError 异常。
  • @dopstar:你是对的!我忘记了默认情况,但我编辑了处理所有其他情况的代码;)
【解决方案2】:

我觉得这个可能还可以:

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]

希望这会有所帮助!

【讨论】:

  • 这根本不是pythonic。我正在努力弄清楚它在做什么。
  • @dopstar 它只是一个具有默认值的字典。它的键是字符串,它的值只是函数。理解代码并不难。
  • 你当然明白,因为你做到了。它的代码看起来太多了。导入使它好像没有它就没有优雅的方式,lambda 增加了火上浇油。然后你也有正常的 dict 并等待,有那个尴尬的[source]。它也效率低下,因为您实际上正在调用所有根本不理想的模型。对于每个“来源”,您将调用所有模型。如果他们正在通过 API 请求更改某些内容,这将非常非常缓慢,并且这样做也可能很危险。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-09-06
  • 2010-10-04
  • 2021-12-08
  • 1970-01-01
  • 2022-12-15
  • 2021-10-08
  • 1970-01-01
相关资源
最近更新 更多