-1

两者之间是否有实际区别

if statement:

if statement == True:

除了第一个更短之外,一个是否具有更高的优先级,还是一个更慢?

编辑:

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

4

2 回答 2

7

那些不相等。Python 允许您在大范围的元素上定义if语句。例如,您可以编写:

if []: # is False
    pass
if 1425: # is True
    pass
if None: # is False
    pass

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

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

例如:

if 0.1:
    pass # will take this branch
else:
    pass

将采用if分支,而:

if 0.1 == True:
    pass
else:
    pass # will take this branch

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

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

class Foo:

    def __eq__(self,other):
        raise Exception()

现在调用Foo() == True将导致:

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

但是,不建议__eq__函数中引发异常(无论如何我强烈建议不要这样做)。

然而,它认为:if <expr>:等价于if bool(<expr>):

鉴于两者相等,显然由于您对等<expr> == True进行了额外的调用,所以速度会变慢。__eq__

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

some_list = []

if some_list: # check if the list is empty
    pass

这也更安全some_list,因为如果可能None(或另一种集合),您仍然检查它是否至少包含一个元素,因此稍微改变主意不会产生巨大影响。

因此,如果您必须写if x == True,通常其本身的真实性会有些奇怪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

以及过度简化版本:

# 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
于 2017-03-17T22:19:38.483 回答
2

if statement: 只要为真(不等于 '0',a至少有一个元素,a有一个键,值对..etcstatement ),则评估为真。intTruelistdict

if statement == Truestatement: 仅当是时才计算为真True,即

>>> print(statement)
True
于 2017-03-17T22:19:15.537 回答