【Class 24】python 的NoneType 对象

实例一: None 是属于 NoneType

a = ''      # 空字符串
b = False   # bool 假
c = []      # 空list
d = set()   # 空集合
e = () 
f = None    # 空     

print( type(a), type(b), type(c), type(d), type(e), type(f))

输出结果:
从上面的例子可以看除,挺奇怪, Nonetype是 NoneType
<class 'str'> <class 'bool'> <class 'list'> <class 'set'> <class 'tuple'> <class 'NoneType'>

实例二:not None == True

None is =====> None is not False
not None is =====> (not None) is True

def function():
    pass
    return None

a = function()

print(type(a))
if a == False:
    print('None is False')
else:
    print('None is not False')

a = not a
print(type(a))
if a == True:
    print('(not None) is True')
else:
    print('(not None) is False')

输出结果:
<class 'NoneType'>
None is not False
<class 'bool'>
(not None) is True

实例三: if else 的判断条件其实是和 bool(xxx)来做对比的

class Test():
    pass

print(bool( Test() ))
if( Test() ):
    print('True')
else:
    print('False')
输出结果:
True
True

class Test_1():
    def __len__(self):
        return 0

print(bool( Test_1() ))
if( Test_1() ):
    print('True')
else:
    print('False')
输出结果:
False
False

你可能感兴趣的:(Python总结)