Python bool 详解 (扒源码)

78 阅读3分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

 一、布尔类型描述

        布尔类型是计算机中最基本的类型,它是计算机二进制世界的体现,一切都是 01 。Python中的布尔类型只有两种值: TrueFalse

(注意:首字母都是大写,与C++、JavaScript中的小写有所不同)

        布尔类型回答的是 是非 问题,那么什么情况下是 True ,什么情况下是 False 呢? Python里面实现了一个 类型对象 叫做 bool ,bool是一个 int 的子类,内置的 TrueFalse 就是bool仅有的两个实例对象。

        python 中布尔值使用常量 True 和 False来表示;注意 T F 大小写

        boolint 的子类(继承 int ),故 True == 1 False == 0 是会返回 Ture

        bool 类型只有两种状态真或假

使用bool我们就可以对对象进行布尔真假判断:

为假的情况有:

print(bool(None))
print(bool(0))
print(bool(0.0))
print(bool(0j))  # 虚数
print(bool(Decimal(0)))  # 0  from decimal import Decimal
print(bool(Fraction(0, 1)))  # 0  from fractions import Fraction
print(bool(''))  # 空字符串
print(bool({}))  # 空字典
print(bool(set()))  # 空集合
print(bool(()))  # 空元组
print(bool([]))  # 空列表

 

二、布尔运算

优先级:not > and > or

运算表达式结果说明
或运算x or y如果x为False则取决于y;如果x为True则不考虑y(1)
与运算x and y如果x为False则不考虑y;如果x为True则取决于y(2)
非运算not x如果x为False则为True,否则为False(2)

说明:

(1) or 是一种“短路运算符”,只有当第一个为False时才去验证第二个。即:两个变量只要有一个为True则为True。

(2) and 也是种“短路运算符”,只有当第一个为True时才去验证第二个。即:两个变量都为True时结果才为True。

(3) not 的优先级比非布尔运算符底,所以 not a == b 解释为 not (a == b) ,并且 a == not b 是语法错误。

print(1 > 2 or 2 > 1)
print(1 < 2 and 1 < 3)
print(not 1 == 2)

三、比较运算

        前面提到,布尔值反应的是“是非”,有比较才有是非。Python中有8中比较运算。它们有相同的优先级,比布尔运算的优先级高。比较运算符可以任意的连写,比如: x < y <=z 相当于 x < y and y <= z

运算含义
<小于
<=小于等于
>大于
>=大于等于
==等于
!=不等于
is是对象
is not不是对象

四、总结

布尔类型(True, False)表示“是非”,是比较运算的结果,是条件判断的结果,从而决定程序的流程和分支走向。

默认情况下,所有类型都可以转化为布尔类型

 

from decimal import Decimal
from fractions import Fraction

print(bool(None))
print(bool(0))
print(bool(0.0))
print(bool(0j))  # 虚数
print(bool(Decimal(0)))  # 0  from decimal import Decimal
print(bool(Fraction(0, 1)))  # 0  from fractions import Fraction
print(bool(''))  # 空字符串
print(bool({}))  # 空字典
print(bool(set()))  # 空集合
print(bool(()))  # 空元组
print(bool([]))  # 空列表

print(1 > 2 or 2 > 1)
print(1 < 2 and 1 < 3)
print(not 1 == 2)

  ​

  五、源码

bool(x) -> bool

Returns True when the argument x is true, False otherwise. The builtins True and False are the only two instances of the class bool. The class bool is a subclass of the class int, and cannot be subclassed.

class bool(int):
    """
    bool(x) -> bool
    
    Returns True when the argument x is true, False otherwise.
    The builtins True and False are the only two instances of the class bool.
    The class bool is a subclass of the class int, and cannot be subclassed.
    """
    def __and__(self, *args, **kwargs): # real signature unknown
        """ Return self&value. """
        pass

    def __init__(self, x): # real signature unknown; restored from __doc__
        pass

    @staticmethod # known case of __new__
    def __new__(*args, **kwargs): # real signature unknown
        """ Create and return a new object.  See help(type) for accurate signature. """
        pass

    def __or__(self, *args, **kwargs): # real signature unknown
        """ Return self|value. """
        pass

    def __rand__(self, *args, **kwargs): # real signature unknown
        """ Return value&self. """
        pass

    def __repr__(self, *args, **kwargs): # real signature unknown
        """ Return repr(self). """
        pass

    def __ror__(self, *args, **kwargs): # real signature unknown
        """ Return value|self. """
        pass

    def __rxor__(self, *args, **kwargs): # real signature unknown
        """ Return value^self. """
        pass

    def __xor__(self, *args, **kwargs): # real signature unknown
        """ Return self^value. """
        pass

​