这个问题已经在这里有一个答案:
在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搜索它,并在这个网站
这就是所谓的short-circuiting
和,是的,Python不支持它:
https://docs.python.org/3/library/stdtypes.html#boolean-operations-and-or-not
如果a and b and c
已经返回b
c
不会评价a
或False
。
x or y
不会评价y
如果x
已经返回True
。
你会发现,这是运营商布尔如何工作在几乎所有的类C语言。