执行一些函数来跟踪是否有任何返回 true

Execute a number of functions keeping track if any returned true

我正在编写代码以从 html 表单中获取数据并修改数据库对象。如果有更改,我只想对数据库对象执行 put(),所以我需要知道是否有任何更改。

到目前为止,我已经尝试了几种方法,我将在代码中进行说明。他们都使用以下设置代码:

def _addFormAttrToModel(self, obj, attr_name, new_attr):
    if hasattr(obj, attr_name):
        current_attr = getattr(obj, attr_name)
        if current_attr == new_attr:
            return False
    setattr(obj, attr_name, new_attr)
    return True
def addFormStringToModel(self, obj, attr_name):
    new_attr = self.request.get(attr_name, None)
    return self._addFormAttrToModel(obj, attr_name, new_attr)

第一个使用 or 来决定是否有任何方法调用 return True。

updated=False
updated = self.addFormStringToModel(customer, "name") or updated
updated = self.addFormStringToModel(customer, "addr") or updated
updated = self.addFormStringToModel(customer, "phone") or updated
if updated:
    customer.put()

我试验过的另一种形式使用了一组:

results= set()
results.add( self.addFormStringToModel(customer, "name"))
results.add( self.addFormStringToModel(customer, "addr"))
results.add( self.addFormStringToModel(customer, "phone"))
if True in results:
    customer.put()

我真正喜欢做的是这样的事情:

updated = self.addFormStringToModel(customer, "name") and \
          self.addFormStringToModel(customer, "addr") and \
          self.addFormStringToModel(customer, "phone")
if updated:
    customer.put()

然而,在更新第一个属性后停止执行。有没有更pythonic的方式?

对列表使用 any

updated = [self.addFormStringToModel(customer, "name"),
          self.addFormStringToModel(customer, "addr"),
          self.addFormStringToModel(customer, "phone")]

if any(updated):

你可以通过列表理解来缩短它:

updated = [self.addFormStringToModel(customer, field)
           for field in ('name', 'addr' 'phone')]
if any(updated)

为了删除冗余代码,您应该首先定义要检查的字段列表:

fields_to_check = ['name', 'addr', 'phone']

然后使用列表聚合将该方法应用于所有值:

updated = [self.addFormStringToModel(customer, field) for field in fields_to_check]

any() 将判断列表中是否有任何结果为真:

if any(updated):
    customer.put()