在Python3中,operator.or_等同于逐位|,而不是逻辑or。为什么逻辑or没有运算符
发布于 2011-10-26 03:30:10
or和and运算符不能表示为函数,因为它们的short-circuiting行为:
False and some_function()
True or some_function()在这些情况下,永远不会调用some_function()。
另一方面,假设的or_(True, some_function())必须调用some_function(),因为函数参数总是在调用函数之前计算。
发布于 2011-10-26 03:26:03
逻辑或是一种控制结构-它决定代码是否正在执行。考虑一下
1 or 1/0这不会抛出一个错误。
相反,无论函数是如何实现的,下面的都会抛出错误:
def logical_or(a, b):
return a or b
logical_or(1, 1/0)发布于 2011-10-26 06:06:54
如果你不介意别人提到的短路行为,你可以试试下面的代码。
all([a, b]) == (a and b)
any([a, b]) == (a or b)
它们都接受包含2个或更多元素的单个集合(如列表、元组甚至生成器),因此以下内容也是有效的:
all([a, b, c]) == (a and b and c)
有关更多详细信息,请查看相关文档:http://docs.python.org/py3k/library/functions.html#all
https://stackoverflow.com/questions/7894653
复制相似问题