如何以更加pythonic的方式更新对象

时间:2017-09-27 11:17:37

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

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

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()
但是,我觉得可以有更好的方法来做到这一点。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

这将做你想要的。它具有与示例函数相同的行为,同时更简洁。

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()