【问题标题】:next() method in Python file object [duplicate]Python文件对象中的next()方法[重复]
【发布时间】:2020-10-28 09:45:17
【问题描述】:

我正在创建一个文件对象并尝试访问其上的 next()。但是解释器抛出错误,指出该函数不存在。

open("scala.txt").next()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: '_io.TextIOWrapper' object has no attribute 'next'

但我遇到的许多讨论都提到 next() 可用。但是当我在 for 循环中使用这个对象时,它工作正常。我能否就上述代码抛出错误的原因寻求帮助。

PS:当我创建自己的生成器并尝试调用 next() 时,我遇到了类似的情况。当我将生成器对象放在 for 循环中时,它工作得很好。

>>> x = (e for e in range(1,10))
>>> x.next()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'generator' object has no attribute 'next'

谢谢!

【问题讨论】:

标签: python-3.x


【解决方案1】:

next() 是内置函数,不是绑定方法。示例:

next(open("scala.txt"))

x = (e for e in range(1, 10))
next(x)

在幕后,对对象调用 next() 往往会调用绑定(但隐藏)的方法 __next__(),这正是您认为的那样。

【讨论】:

  • 啊,非常感谢!!这对我帮助很大!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-05-21
  • 2014-03-09
  • 1970-01-01
  • 2015-03-31
  • 1970-01-01
  • 2016-04-20
  • 1970-01-01
相关资源
最近更新 更多