【问题标题】:How to update an object in a more pythonic way如何以更 Pythonic 的方式更新对象
【发布时间】:2017-09-27 11:17:37
【问题描述】:

目前,我正在更新如下购物清单项目

def update_item(self, name, price, quantity, shoppinglist):
        # updates self If the variable is not equal to the name None
        if name != "None":
            self.name = name
        if price != "None":
            self.price = price
        if quantity != "None":
            self.quantity = quantity
        if shoppinglist != "None":
            self.shoppinglist_id = shoppinglist.id
        db.session.commit()

不过,我觉得可能有更好的方法来做到这一点。任何帮助将不胜感激。

【问题讨论】:

  • 您试图一次更新所有内容并使用“无”字符串作为指标值的事实使事情变得复杂。为什么不为每个设置一个单独的设置器?还是传入字典?
  • 这是一个 Flask API,使用字符串“None”只是为了表示用户不想更新该字段。如果我对每个都使用设置器,他们是否仍应检查值是否等于“无”??
  • 这感觉很糟糕。您应该设置每个变量,即使该变量设置为“无”。这样,当您尝试访问变量时,它就不会崩溃。
  • @ddg 由于它是一种更新方法,因此应用程序不会崩溃,因为如果值未更新,它将保留其先前的值
  • 哦,对不起,没意识到

标签: python python-2.7 python-3.x flask-sqlalchemy


【解决方案1】:

这会做你想做的事。它与您的示例函数具有相同的行为,但更简洁。

def update_items(self, **kwargs):
    assert set(kwargs) == {"name", "price", "quantity", "shoppinglist"}

    for key, val in kwargs.items():
        if val!="None": 
            setattr(self, key, val)

    db.session.commit()

如果你想要带有默认值的可选参数,那么你应该这样做。

def update_item(self, name=None, price=None, quantity=None, shoppinglist=None):
    # updates self If the variable is not equal to the name None
    if name is not None:
        self.name = name
    if price is not None:
        self.price = price
    if quantity is not None:
        self.quantity = quantity
    if shoppinglist is not None:
        self.shoppinglist_id = shoppinglist.id
    db.session.commit()

您可以结合使用这两种方法:

def update_items(self, **kwargs):
    okay = {"name", "price", "quantity", "shoppinglist"}

    for key, val in kwargs.items():
        if val in okay and val!="None": 
            setattr(self, key, val)

    db.session.commit()

【讨论】:

  • 问题是我事先不知道用户想要更新什么值。即他/她可能想更新价格,而另一个人可能想更新名称
猜你喜欢
  • 2014-03-01
  • 2014-09-17
  • 1970-01-01
  • 1970-01-01
  • 2011-12-13
  • 2020-06-04
  • 1970-01-01
  • 1970-01-01
  • 2017-03-09
相关资源
最近更新 更多