为什么运算符模块缺少`and`和`or`? [英] Why is operator module missing `and` and `or`?
问题描述
运算符模块可轻松避免不必要的功能和lambda 在这种情况下:
operator module makes it easy to avoid unnecessary functions and lambdas in situations like this:
import operator
def mytest(op, list1, list2):
ok = [op(i1, i2) for i1, i2 in zip(list1, list2)]
return all(ok)
mytest(operator.eq, [1, 2, 3], [1, 2, 3]) # True
mytest(operator.add, [-1, 2, -3], [1, -2, 33]) # False
好吧,现在我需要执行i1 and i2
,但是令我惊讶的是,在操作员模块中找不到and
!同样适用于or
!我知道,and
并非完全是 operator ,它是一个 keyword ,但not
以及is
甚至del
都是关键字,并且都是包括在内.
Well, now I need to do i1 and i2
, but to my surprise, I can't find and
in the operator module! And the same applies to or
! I know, and
is not exactly operator, it's a keyword, but not
, along with is
and even del
, are all keywords and all are included.
那是什么故事?他们为什么失踪了?
So what's the story? Why are they missing?
推荐答案
因为您不能将布尔运算符转换为python函数.函数始终会评估其参数,而布尔运算符则不会.向操作员模块添加and
和or
还将需要添加一种特殊类型的函数(例如lisp"macros"),该函数可按需评估其参数.显然,这不是python设计人员想要的.考虑:
Because you cannot convert boolean operators into python functions. Functions always evaluate their arguments, and boolean operators do not. Adding and
and or
to the operators module would also require adding a special kind of functions (like lisp "macros") that evaluate their arguments on demand. Obviously, this is not something python designers ever wanted. Consider:
if obj is not None and obj.is_valid():
....
您不能以功能形式编写它.像这样的尝试
you cannot write this in a functional form. An attempt like
if operator.xyz(obj is not None, obj.is_valid())
如果obj
实际上是None
,则
将失败.
will fail if obj
is actually None
.
这篇关于为什么运算符模块缺少`and`和`or`?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!