Python中的布尔类型的注意点

来源:互联网 发布:linux自动挂载硬盘 编辑:程序博客网 时间:2024/05/16 12:56

一.前戏:

3. Data model

3.2. The standard type hierarchy¶

Booleans (bool)

These represent the truth values False and True. The two objects representing the values False and True are the only Boolean objects. The Boolean type is asubtypeof the integer type, and Boolean valuesbehavelike the values 0 and 1, respectively, in almost all contexts, the exception being that when converted to a string, the strings "False" or "True" are returned, respectively.

The rules for integer representation are intended to give the most meaningful interpretation of shift and mask operations involving negative integers.

使用整数表示的规则主要是为了在涉及到负数的移位和掩码操作更有意义

4. Built-in Types

4.1. Truth Value Testing

Any object can be tested for truth value, for use in an if or while condition or as operand of the Boolean operations below. The following values are consideredfalse:

  • None

  • False

  • zero of any numeric type, for example, 00.00j.

  • any empty sequence, for example, ''()[].

  • any empty mapping, for example, {}.

  • instances of user-defined classes, if the class defines a __bool__() or __len__() method, when that method returns the integer zero or bool value False. [1]

All other values are considered true — so objects of many types are always true.

Operations and built-in functions that have a Boolean result always return 0 or False for false and 1 or True for true, unless otherwise stated. (Important exception: the Boolean operations or and and always return one of their operands.)


1.python使用布尔类型表示真值
2.python中布尔类型是int型的子类,布尔值False, True行为类似于0, 1
----------------------------------------------------------------------------------------------------------------------------------------------------------
二.主题:
经常听到朋友说python中布尔值False和所有空类型是等价,在日常使用中确实很难发现上述API中用词(高亮部分)的深层含义
e.g.
1.可以被认为是True的值

def f():passclass Foo():passif 3:print(3)if '3':print('3')if (3,):print((3,))if[3]:print([3])if {3:'3'}:print({3:'3'})if f:print(f)if Foo:print(Foo)'''输出:33(3,)[3]{3: '3'}<function f at 0x0000018CDD713E18><class '__main__.Foo'>'''


2.可以被认为是False的值

if 0:print('0--if')else:print('0--else')if '':print('string--if')else:print('string--else')if ():print('tuple--if')else:print('tuple--else')if []:print('list--if')else:print('list--else')if {}:print('dic--if')else:print('dic--else')'''输出:0--elsestring--elsetuple--elselist--else{}--else'''
3.可以被认为是xxx和是xxx是不同的概念

if 0:print('0--if')else:print('0--else')if '':print('string--if')else:print('string--else')if ():print('tuple--if')else:print('tuple--else')if []:print('list--if')else:print('list--else')if {}:print('dic--if')else:print('dic--else')'''输出:0--elsestring--elsetuple--elselist--else{}--else'''