注意:以下两种写法是有区别的。
if x
和if x is not None
if not x
和if x is None
python里面的其他值也被检测为False
。最常见的例子就是空列表,bool([])
也返回False
。但是,空列表有一个隐含的意思,它不等于None
!!None
意味着没有值,而空列表意味着零个值,这在语义上是不同的!
示例代码1:
x = None
print('test1' + '-' * 50)
if x:
print('if x')
print('test2' + '-' * 50)
if x is not None:
print('if x is not None')
print('test3' + '-' * 50)
if not x:
print('if x')
print('test4' + '-' * 50)
if x is None:
print('if x is not None')
print('test5' + '-' * 50)
print(bool(x))
运行结果:
示例代码2: 【空列表不等于None】【
python会自动给非boolean类型进行bool判断的时候转换成boolean类型】
x = []
print('test1' + '-' * 50)
if x:
print('if x')
print('test2' + '-' * 50)
if x is not None:
print('if x is not None')
print('test3' + '-' * 50)
if not x:
print('if x')
print('test4' + '-' * 50)
if x is None:
print('if x is not None')
print('test5' + '-' * 50)
print(bool(x))
运行结果:
示例代码3:
# x = [0]
x = [1] # 这儿写0和1是一样的
print('test1' + '-' * 50)
if x:
print('if x')
print('test2' + '-' * 50)
if x is not None:
print('if x is not None')
print('test3' + '-' * 50)
if not x:
print('if x')
print('test4' + '-' * 50)
if x is None:
print('if x is not None')
print('test5' + '-' * 50)
print(bool(x))
运行结果:
示例代码4:
x = 0
print('test1' + '-' * 50)
if x:
print('if x')
print('test2' + '-' * 50)
if x is not None:
print('if x is not None')
print('test3' + '-' * 50)
if not x:
print('if x')
print('test4' + '-' * 50)
if x is None:
print('if x is not None')
print('test5' + '-' * 50)
print(bool(x))
运行结果:
示例代码5:
x = 1
print('test1' + '-' * 50)
if x:
print('if x')
print('test2' + '-' * 50)
if x is not None:
print('if x is not None')
print('test3' + '-' * 50)
if not x:
print('if x')
print('test4' + '-' * 50)
if x is None:
print('if x is not None')
print('test5' + '-' * 50)
print(bool(x))
运行结果:
示例代码6: 【自定义类】【x是被__bool__
初始化的】
class Foo(object):
def __bool__(self):
print("Foo将会被检测为Boolean类型")
return True
x = Foo()
print('test1' + '-' * 50)
if x:
print('if x')
print('test2' + '-' * 50)
if x is not None:
print('if x is not None')
print('test3' + '-' * 50)
if not x:
print('if x')
print('test4' + '-' * 50)
if x is None:
print('if x is not None')
print('test5' + '-' * 50)
print(bool(x))
运行结果:
示例代码7:
class Foo(object):
def __bool__(self):
print("Foo将会被检测为Boolean类型")
return False
x = Foo()
print('test1' + '-' * 50)
if x:
print('if x')
print('test2' + '-' * 50)
if x is not None:
print('if x is not None')
print('test3' + '-' * 50)
if not x:
print('if x')
print('test4' + '-' * 50)
if x is None:
print('if x is not None')
print('test5' + '-' * 50)
print(bool(x))
运行结果: