if语句和if equals语句之间的区别

Mas*_*tla -1 python if-statement python-3.x truthiness

两者之间是否存在实际差异?

if statement:
Run Code Online (Sandbox Code Playgroud)

if statement == True:
Run Code Online (Sandbox Code Playgroud)

除了第一个更短,一个有更高的优先权,还是一个更慢?

编辑:

我意识到这可能不是很清楚,但statement通常是这样statement = True.

Wil*_*sem 7

那些不平等.Python允许您在大量元素定义if语句.你可以写一下:

if []: # is False
    pass
if 1425: # is True
    pass
if None: # is False
    pass
Run Code Online (Sandbox Code Playgroud)

基本上如果你写if <expr>,Python将评估表达式的真实性.这是预定义的数字(int,float,complex,不等于零),一些内置集合(list,dict,不为空),你可以定义一个__bool____len__任意对象自己上.你可以通过调用来获得对象的真实性bool(..).例如bool([]) == False.

示例if x不等于if x == True:

例如:

if 0.1:
    pass # will take this branch
else:
    pass
Run Code Online (Sandbox Code Playgroud)

将采取if分支,而:

if 0.1 == True:
    pass
else:
    pass # will take this branch
Run Code Online (Sandbox Code Playgroud)

不会采取if分支.这是因为数字是等于True,如果它是一个(1,1L,1+0j,...).而bool(x)数字True是否x非零.

也可以定义一个==引发异常的对象.喜欢:

class Foo:

    def __eq__(self,other):
        raise Exception()
Run Code Online (Sandbox Code Playgroud)

现在打电话Foo() == True会导致:

>>> Foo() == True
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in __eq__
Exception
Run Code Online (Sandbox Code Playgroud)

但是,不建议__eq__函数中引发异常(无论如何我强烈反对它).

然而,它认为:if <expr>:相当于if bool(<expr>):.

鉴于两者相等,显然<expr> == True会因为你额外的呼叫__eq__等而变慢,等等.

此外,检查集合是否为空时通常更为惯用:

some_list = []

if some_list: # check if the list is empty
    pass
Run Code Online (Sandbox Code Playgroud)

这也更安全,因为如果有可能,some_listNone(或其他类型的集合),你还是检查它是否保持至少一个元素,所以改变主意一点不会有显着的影响.

所以,如果你有写if x == True,通常有一些怪异truthness的的x本身.

关于真相的一些背景:

正如文档中指定的那样(Python-2.x/Python-3.x).有一种方法可以解决真相.

,它被评估为(过度简化版本,更多"伪Python"代码来解释它是如何工作的):

# Oversimplified (and strictly speaking wrong) to demonstrate bool(..)
# Only to show what happens "behind the curtains"
def bool(x):
    if x is False or x is None:
        return False
    if x == 0 or x == 0.0 or x == 0L or x == 0j:
        return False
    if x is () or x == [] or x == '' or x == {}:
        return False
    if hasattr(x,'__nonzero__'):
        y = x.__nonzero__()
        return y != 0 and y != False
    if hasattr(x,'__len__'):
        return x.__len__() != 0
    return True
Run Code Online (Sandbox Code Playgroud)

过度简化版本:

# Oversimplified (and strictly speaking wrong) to demonstrate bool(..)
# Only to show what happens "behind the curtains"
def bool(x):
    if x is False or x is None:
        return False
    if x == 0 or x == 0.0 or x == 0j:
        return False
    if x is () or x == [] or x == '' or x == {}:
        return False
    if hasattr(x,'__bool__'):
        return x.__bool__() is True
    if hasattr(x,'__len__'):
        return x.__len__() != 0
    return True
Run Code Online (Sandbox Code Playgroud)

  • 不,惯用你写`if some_list:`检查`some_list`是否包含元素.通常对象的*真性*是有意义的,因此最好使用那个. (4认同)
  • 值得一提的是 - 与数字相比,`True == 1`,`bool(x)`是`x .__ nonzero __()`或`x .__ bool __()`for Py2/Py3 (2认同)

归档时间:

查看次数:

113 次

最近记录:

8 年,8 月 前