【发布时间】:2019-06-27 12:39:18
【问题描述】:
在 Python 3 中,我必须检查函数参数中没有发生 3 个条件,因此,我创建了 3 个函数:
def check_lenght(string_id):
# if length is right, return True, otherwise, False
def check_format(string_id):
# return True if some internal format has to be used, in another case, False
def check_case_num(string_id):
# manual iteration to check if certain characters are not contained, return True, otherwise, False
def valid_product_code(id_str):
return check_lenght(id_str) and check_format(id_str) and check_case_num(id_str)
所以,有 3 个函数,其中一个迭代字符串,这是一个潜在的非常繁重的操作。 但是,如果一个函数已经返回 False,则无需检查其余函数,我们知道逻辑 AND 将返回 False,从而能够降低计算成本。
所以,我想知道 Python(CPython 或其他实现)是否对此进行了优化,因此,return check_lenght(id_str) and check_format(id_str) and check_case_num(id_str) 的使用是正确的,或者最好一一检查这些函数并尽快返回 False其中第一个是 False,具有更优化但可能不太可读的解决方案。
如何在 Python 中评估此表达式?
我试图在谷歌上搜索这个问题的答案,也在这个网站上找到答案
【问题讨论】:
标签: python python-3.x optimization evaluation