错误说明:“ NoneType”对象不可迭代
在python2中,NoneType是None的类型。在Python3中,NoneType是None的类,例如:
>>> print(type(None)) #Python2
<type 'NoneType'> #In Python2 the type of None is the 'NoneType' type.
>>> print(type(None)) #Python3
<class 'NoneType'> #In Python3, the type of None is the 'NoneType' class.
遍历具有值None的变量失败:
for a in None:
print("k") #TypeError: 'NoneType' object is not iterable
Python方法如果不返回值,则返回NoneType:
def foo():
print("k")
a, b = foo() #TypeError: 'NoneType' object is not iterable
您需要像这样检查NoneType的循环结构:
a = None
print(a is None) #prints True
print(a is not None) #prints False
print(a == None) #prints True
print(a != None) #prints False
print(isinstance(a, object)) #prints True
print(isinstance(a, str)) #prints False
Guido说只用于is
检查,None
因为is
它对身份检查更可靠。不要使用相等运算,因为那些运算会加剧自身的泡沫。 Python的编码样式指南-PEP-008
类型是偷偷摸摸的,可以从lambdas偷偷溜走:
import sys
b = lambda x : sys.stdout.write("k")
for a in b(10):
pass #TypeError: 'NoneType' object is not iterable
NoneType不是有效的关键字:
a = NoneType #NameError: name 'NoneType' is not defined
None
和字符串的串联:
bar = "something"
foo = None
print foo + bar #TypeError: cannot concatenate 'str' and 'NoneType' objects
这里发生了什么?
Python的解释器将您的代码转换为pyc字节码。Python虚拟机处理了字节码,它遇到了一个循环结构,该结构表示对包含None的变量进行迭代。通过__iter__
在None上调用该方法来执行该操作。
None没有__iter__
定义方法,因此Python的虚拟机会告诉您所看到的内容:NoneType没有__iter__
方法。
这就是为什么Python的鸭式思维被认为是不好的。程序员使用变量进行了完全合理的操作,在运行时它被None污染,python虚拟机试图继续运行,并在地毯上吐出一堆无关紧要的废话。
Java或C ++没有这些问题,因为不允许您编译此类程序,因为您没有定义发生None时的处理方法。Python允许您执行很多在特殊情况下无法预期的工作,从而为程序员提供了很多上锁的绳索。Python是一个肯定的人,当它像Java和C ++那样阻止您伤害自己时,说是肯定的先生。
None
被强制为序列时,它必须产生一个完全无害的空序列。