AttributeError: 'generator' オブジェクトに Python の 'next' 属性がありません
属性は、オブジェクトまたはクラスに関連する値です。 メソッドでサポートされていないタイプのオブジェクトの属性を呼び出すと、Python で AttributeError が発生します。
たとえば、int オブジェクトで split() メソッドを使用すると、AttributeError が返されます。これは、int オブジェクトが split() メソッドをサポートしていないためです。
Python 3 では、イテレータに関連付けられた .next メソッドはありません。 その結果、generator オブジェクトで .next メソッドを使用しようとすると、AttributeError が発生します。
このチュートリアルでは、Python で AttributeError: 'generator' object has no attribute 'next' を修正する方法を説明します。
AttributeError: 'generator' object has no attribute 'next' エラーを Python で修正
Python 3 で yield ステートメントを使用した場合の AttributeError の例を次に示します。
def get_data(n):
for i in range(n):
yield i
a = get_data(20)
for i in range(10):
print(a.next())
出力:
Traceback (most recent call last):
File "c:\Users\rhntm\myscript.py", line 6, in <module>
print(a.next())
AttributeError: 'generator' object has no attribute 'next'
ご覧のとおり、コード print(seq.next()) を含む AttributeError が 6 行目にあります。 これは、.next メソッドを使用してイテレータから次のアイテムを取得したためです。
.next メソッドは、Python 3 の組み込み関数 next() に置き換えられました。以下に示すように、next 関数を使用してこのエラーを修正できます。
def get_data(n):
for i in range(n):
yield i
a = get_data(20)
for i in range(10):
print(next(a))
出力:
0
1
2
3
4
5
6
7
8
9
Python 2 では .next メソッドを使用できますが、Python 3 では例外 AttributeError がスローされます。
これで、Python でエラー 'generator' object has no attribute 'next' を解決する方法がわかりました。 このソリューションがお役に立てば幸いです。
