None <==>不存在
1、值
不等于空字符串穿、空的长列表、0、False(假)
举例说明:
a=''
b=False
c=[]
print(a==None)
print(b==None)
print(c==None)
输出:
>>> False
False
False
2、类型
print(a is None)
#>>> False
print(type(None))
#>>><class 'NoneType'>
经典误区:
def fun():
return None
a=fun()
if not a:
print('S')
else:
print('F')
if a is None:
print('S')
else:
print('F')
#>>>S
#S
输出:输出结果一样就认为是相同类型(错误!!!)
>>>S
S
跳出误区:
a1=[]
if not a1:#判空操作
print('S')
else:
print('F')
#>>>S
if a1 is None:#None不等同于空列表,类型不同,所以不能做判空操作
print('S')
else:
print('F')#类型不同
#>>>F
深入学习辨析:
#自定义的对象判空
class Test():
def __bool__(self):
return False
def __len__(self):
return 0
test=Test()
#None
print(bool(None))
print(bool([]))
print(bool(test))#>>>False test存在但是>>>False 返回结果取决于内置的bool放法,只运行了bool放法没有调用len方法
print(bool(Test))#>>>True
'''
#当__bool__(self)方法不存在时返回False
print(bool(Test))#>>>False
#当__len__(self)方法返回结果不是0而是8
print(bool(Test))#>>>True
#当__len__(self)方法返回结果不是0而是True
print(bool(Test))#>>>True
'''
if test:
print('S')
else:
print('F')
输出结果:
>>>False
False
False
True
F