【问题标题】:Python evaluates 0 as FalsePython 将 0 评估为 False
【发布时间】:2012-09-11 21:48:43
【问题描述】:

在 Python 控制台中:

>>> a = 0
>>> if a:
...   print "L"
... 
>>> a = 1
>>> if a:
...   print "L"
... 
L
>>> a = 2
>>> if a:
...   print "L"
... 
L

为什么会这样?

【问题讨论】:

标签: python boolean


【解决方案1】:

在Python中,boolint的子类,False的值是0;即使值没有在 if 语句(它们是)中隐式转换为 boolFalse == 0 也是正确的。

【讨论】:

  • 0 == False 为真但不完全相关,None == False 为假,但if None: 仍被评估为假值(以及空映射等)
【解决方案2】:

0 是 python 中的假值

假值:from (2.7) documentation:

任何数字类型的零,例如,0、0L、0.0、0j。

【讨论】:

    【解决方案3】:

    if 子句中的任何内容都隐含地调用了bool。所以,

    if 1:
       ...
    

    真的是:

    if bool(1):
       ...
    

    bool 调用__nonzero__1 表示对象是True 还是False

    演示:

    class foo(object):
        def __init__(self,val):
            self.val = val
        def __nonzero__(self):
            print "here"
            return bool(self.val)
    
    a = foo(1)
    bool(a)  #prints "here"
    if a:    #prints "here"
        print "L"  #prints "L" since bool(1) is True.
    

    1__bool__ on python3.x

    【讨论】:

    • 作为旁注,我相信 __nonzero__ 在 py3k 中更改为 __bool__
    • 我反过来看,true对应1,是int的子类
    【解决方案4】:

    我认为它只是以 0 或非 0 来判断:

    >>> if 0:
        print 'aa'
    
    >>> if not 0:
        print 'aa'
    
    
    aa
    >>> 
    

    【讨论】:

    • 这是什么意思?你print 两种情况的输出相同,什么都不解释
    • @Chris_Rands 如果if 0,则没有打印
    【解决方案5】:

    首先,python 中的一切都是对象。因此,你的 0 也是一个对象,具体来说,是一个内置对象。

    以下是被认为是假的内置对象:

    1. 定义为假的常量:无和假。
    2. 任何数字类型的零:0, 0.0, 0j, Decimal(0), Fraction(0, 1)
    3. 空序列和集合:''、()、[]、{}、set()、range(0)

    因此,当您将 0 置于 if 或 while 条件或布尔运算中时,将对其进行真值测试。

    # call the __bool__ method of 0
    >>> print((0).__bool__())
    False
    
    # 
    >>> if not 0:
    ...     print('if not 0 is evaluated as True')
    'if not 0 is evaluated as True'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-24
      • 2019-04-19
      • 1970-01-01
      • 2015-03-15
      • 2016-08-25
      • 1970-01-01
      • 1970-01-01
      • 2012-05-18
      相关资源
      最近更新 更多