繁体   English   中英

实现此 Python 代码的最佳方法是什么

[英]What is the best way to implement this Python code

我这里有这个简单的代码:

def myFunction(a: my_enumA, b: my_enumB, c: my_enumC):
  
  if a:
    update_a = update_from_db_a(a=a)
  else:
    update_a = True
  
  if b:
    update_b = update_from_db_b(b=b)
  else:
    update_b = True
  
  if c:
    update_c = update_from_db_c(c=c)
  else:
    update_c = True
    
  if update_a and update_b and update_c:
    return True
  else:
    return False

我确定为此存在设计模式,但我不知道名称。

实现它的最佳 Pythonic 方式是什么? 也许有设计模式?

您可以将每个第一个if转换为一个语句:

# If a is False, value is True
# If a is True, value is update_from_db_a(a=a)
update_a = not a or update_from_db_a(a=a)

请注意,如果not a is True (又名a is False ),它将不会执行条件的下一部分(它不会调用update_from_db_a )。

此外,您的 function 仅在条件为 True 时才会返回True ,因此您可以像这样重写它:

# If condition is True, returns True
# If condition is False, returns False
return update_a and update_b and update_c

结果代码:

def myFunction(a: my_enumA, b: my_enumB, c: my_enumC):
    update_a = not a or update_from_db_a(a=a)
    update_b = not b or update_from_db_b(b=b)
    update_c = not c or update_from_db_c(c=c)
    return update_a and update_b and update_c

您可以压缩所有条件并将它们传递给all()

def myFunction(a: my_enumA, b: my_enumB, c: my_enumC):
    return all([
        not a or update_from_db_a(a=a),
        not b or update_from_db_b(b=b),
        not c or update_from_db_c(c=c)
    ])

确保将它们包装在可迭代对象中,例如listtupleset ,而不是在生成器中。 否则all()将在第一个错误条件下终止。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM