的Python:优化和评估[复制]

问题描述 投票:2回答:2

这个问题已经在这里有一个答案:

在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,能够使这个少计算成本。

所以,我想知道如果Python的(CPython的或其他的实现)是优化这一点,因此,return check_lenght(id_str) and check_format(id_str) and check_case_num(id_str)的使用是正确的,或者如果它会更好地检查这些功能也一一并尽快返回false作为他们的第一个是假,具有更优化的,但是也许少可读溶液。

如何表达在Python进行评估?

我试图找到这个问题的答案google搜索它,并在这个网站

python python-3.x optimization evaluation
2个回答
2
投票

这就是所谓的short-circuiting和,是的,Python不支持它:

https://docs.python.org/3/library/stdtypes.html#boolean-operations-and-or-not


2
投票

如果a and b and c已经返回b c不会评价aFalse

x or y不会评价y如果x已经返回True

你会发现,这是运营商布尔如何工作在几乎所有的类C语言。

© www.soinside.com 2019 - 2024. All rights reserved.