TypeError: 'NoneType' object is not iterable
是什么意思?例子:
for row in data: # Gives TypeError!
print(row)
原文由 Alex Gordon 发布,翻译遵循 CC BY-SA 4.0 许可协议
TypeError: 'NoneType' object is not iterable
是什么意思?例子:
for row in data: # Gives TypeError!
print(row)
原文由 Alex Gordon 发布,翻译遵循 CC BY-SA 4.0 许可协议
在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.
for a in None:
print("k") #TypeError: 'NoneType' object is not iterable
def foo():
print("k")
a, b = foo() #TypeError: 'NoneType' object is not iterable
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
import sys
b = lambda x : sys.stdout.write("k")
for a in b(10):
pass #TypeError: 'NoneType' object is not iterable
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 没有定义 __iter__
方法,所以 Python 的虚拟机告诉你它看到了什么:NoneType 没有 __iter__
方法。
这就是为什么 Python 的 duck-typing 意识形态被认为是不好的。程序员对一个变量做了一些完全合理的事情,但在运行时它被 None 污染了,python 虚拟机试图坚持下去,并在地毯上吐出一堆不相关的废话。
Java 或 C++ 没有这些问题,因为这样的程序将不允许编译,因为您没有定义在 None 发生时要做什么。 Python 允许你做很多在特殊情况下不能正常工作的事情,从而给了程序员很多上吊的机会。 Python 是一个唯唯诺诺的人,当它阻止你伤害自己时说是,先生,就像 Java 和 C++ 所做的那样。
原文由 Eric Leschinski 发布,翻译遵循 CC BY-SA 4.0 许可协议
2 回答5.2k 阅读✓ 已解决
2 回答1.1k 阅读✓ 已解决
4 回答1.4k 阅读✓ 已解决
3 回答1.3k 阅读✓ 已解决
3 回答1.3k 阅读✓ 已解决
2 回答884 阅读✓ 已解决
1 回答1.8k 阅读✓ 已解决
这意味着
data
的值是None
。