from urllib import urlopen
with urlopen('https://www.python.org') as story:
story_words = []
for line in story:
line_words = line.split()
for words in line_words:
story_words.append(word)
错误消息:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: addinfourl instance has no attribute '__exit__'
我不明白上面的代码有什么问题以及如何解决?
系统信息:ubuntu oracle虚拟框中的python 2.7。
您可以在Python2.7中尝试以下操作:
该错误是由以下行引起的:
不能在
with...as
语句中使用任何随机对象。有两种方法可以解决此问题:
解决方案1:使用
contextlib.closing
:解决方案2:不要使用
with...as
语句;而是将值赋给变量:为什么会这样?
不能在
with ... as
语句中使用任何随机对象。只有那些具有两个神奇方法的对象才能工作:
__enter__
和__exit__
在它们上实现。这些方法统称为“上下文管理器”。关于这个的介绍性教程可以在下面找到。之所以引发
AttributeError
,是因为没有为urlopen
实现任何上下文管理器(即它没有为其定义__enter__
和__exit__
方法)。这让您有两个选择:
with...as
语句。with...as
语句。(注意:在Python 3中,
urlopen
没有上下文管理器,因此可以在with...as
语句中使用。)教程:如何实现上下文管理器?
要使对象在
with...as
语句中工作,首先需要实现该对象的上下文管理器。简单地说,您需要为该对象/类定义__enter__
和__exit__
方法。一定要读these docs on context managers。
示例:
相关问题 更多 >
编程相关推荐