ATTRIBUTEERROR

Python AttributeError の直し方|'NoneType' object has no attribute などを逆引き

'NoneType' object has no attribute 'append' など、表示された英語の「型」から原因と直し方を引けます。

🎯 対象: AttributeError で止まった初心者 ⏱️ 読了: 約9分 🧪 実測: Windows 11・Python 3.15.2/3.14.7/3.12.10・2026-11-27

結論:AttributeError は「その型(モジュール)に、その名前の属性・メソッドが無い」ときに出ます。'<型>' object has no attribute '<名前>' の最初の引用符、つまり「型」を見てください。よく出るのは 'NoneType'=値が None だったケースです。

1. 結論:エラー文の型別の早見表

エラー文の書き出し主な原因直し方
'NoneType' objectsort() の戻り値を代入・return 忘れ・re.match() が不一致代入しない・if m:
'str'・'list'・'dict'・'tuple'・'int'・'bytes' object型の取り違えその型のメソッドを使う
module 'math'打ち間違い・datetime.now()ヒントの名前に直す
module 'random' ... (consider renaming ...)・partially initialized module自作の random.py など・循環 importファイル名を変える
'User' object・type object 'A'自作クラスの self. 忘れ・字下げself.count = 0
no __dict__ for setting new attributes・has no setter代入できない相手に代入setter を足す
'DataFrame' object・module 'numpy'ライブラリの版で消えた名前pd.concat()・float

module 'flet' has no attribute 'app'・'ElevatedButton' は Flet の名前変更です。Flet 入門の対応表を見てください。

🧪
検証環境(2026年11月27日実測)

Windows 11 Pro・Python 3.15.2・3.14.7・3.12.10。3.14 系の最新は 3.14.10 ですが、試したのは 3.14.7 です。pandas 3.1.1・NumPy 2.5.5 は 3.14.7 だけで試しました。

2. エラー文の読み方と調べ方

AttributeError: 'NoneType' object has no attribute 'append'

1つ目の引用符が実際の値の型、2つ目が探した名前です。この例は「None に append は無い」で、直すのは None を入れた行です。

Did you mean のヒントは 3.15 で書き方が変わった

'abc'.uper()ヒントの部分
3.15.2Did you mean '.upper' instead of '.uper'?
3.14.7・3.12.10Did you mean: 'upper'?

ヒント自体は 3.10 で追加され、3.15 の形は gh-144285 で入りました。いつも出るわけではなく、json.parse() や自作クラスの u.nmae は3版ともヒントなしでした。

type()・dir()・hasattr()・getattr() で確かめる

obj = "abc"
print(type(obj))                              # <class 'str'>
print(hasattr(obj, "append"))                 # False
print(getattr(obj, "append", None))           # None
print([n for n in dir(obj) if "upp" in n])    # ['isupper', 'upper']

3. 'NoneType' object has no attribute の直し方

値が None のまま、メソッドを呼んでいます。次の6つは3版とも同じ最終行でした。

書いたコード'NoneType' object has no attribute の後
nums = nums.sort() → nums.append(4)'append'
a = a.append(1) → a.append(2)'append'
return の無い関数の戻り値に .get('name')'get'
re.match(r'[0-9]+', 'abc').group()'group'
{}.get('user').upper()'upper'
x = print('hi') → x.strip()'strip'

sort()・append() の戻り値を代入しない

sort()・append() はリストそのものを書き換え、None を返します。

nums = [3, 1, 2]
nums.sort()                 # 代入しない
nums.append(4)
print(nums)                 # [1, 2, 3, 4]
print(sorted([3, 1, 2]))    # [1, 2, 3]

同じ原因で [0] を付けると 'NoneType' object is not subscriptable です。

関数の return 忘れ

return の無い関数は None を返します(return の書き方)。

def load():
    data = {"name": "taro"}
    return data             # 忘れると None が返る

print(load().get("name"))   # taro

re.match() が不一致・dict.get() で無いキー

re.match() は一致しないと None を返すので、if m: か is not None で分けてから使います。

import re

m = re.match(r"[0-9]+", "abc")
print(m.group() if m else "一致なし")       # 一致なし

if (m := re.match(r"[0-9]+", "123abc")) is not None:
    print(m.group())                       # 123

d = {}
print(d.get("user", "").upper() or "(空)") # (空):既定値 "" なら None にならない

辞書の読み方は KeyError の直し方にあります。

4. 'str'・'list'・'dict' などの取り違え

行頭の AttributeError: '型' object has no attribute は省き、encode・decode の行はヒントだけ載せました。

コード3.15.23.14.7・3.12.10直し方
'abc'.append('d')'append's + "d" → abcd
['a b', 'c d'].split()'split'[w.split() for w in words]
[1].add(2)'add'. Did you mean to use a 'set' object?'add'リストは append()
(1, 2).append(3)'append'. Did you mean to use a 'list' object?'append'リストで作る
{1}.append(2)'append'(3.15.2 もヒントなし)st.add(2)
{'name': 'taro'}.name'name'user["name"]
n = 5 → n.append(1)'int' object has no attribute 'append'値を type() で確かめる
b'abc'.encode()Did you mean '.decode' instead of '.encode'?Did you mean: 'decode'?b"abc".decode("utf-8")
'abc'.decode('utf-8')Did you mean '.encode' instead of '.decode'?Did you mean: 'encode'?"abc".encode("utf-8")

3.15 では「別の型のつもりだった」ヒントが付きます。list の add に set、tuple の append に list を勧める表示で、gh-146406 で入りました(push に .append を勧める例は3.15 の変更点)。辞書の値は ["name"] で読みます(辞書の基本)。

5. module 'x' has no attribute(打ち間違い・datetime)

コード3.15.23.14.7・3.12.10
math.sqroot(4)Did you mean '.sqrt' instead of '.sqroot'?Did you mean: 'sqrt'?
os.getCwd()Did you mean '.getcwd' instead of '.getCwd'?Did you mean: 'getcwd'?
import tkinter → tkinter.messagebox.showinfo(...)未実行module 'tkinter' has no attribute 'messagebox'(ヒントなし)
json.parse('{}')module 'json' has no attribute 'parse'(ヒントなし)
import datetime → datetime.now()Did you mean '.datetime.now' instead of '.now'?ヒントなし

import tkinter.messagebox か from tkinter import messagebox を足すと AttributeError は出なくなりました(tkinter の部品一覧)。JSON の文字列を読むのは json.loads() です(json の例)。

datetime モジュールの中には、同じ名前のクラスがあります。now() はクラスの側にあるので、書き方は次のどちらかです。

import datetime
print(datetime.datetime.now())    # モジュール.クラス.now()

from datetime import datetime as dt
print(dt.now())                   # クラスを直接 import

6. consider renaming:自作の random.py が原因のとき

実行したファイルと同じフォルダに random.py があると、標準ライブラリの random の代わりにそちらが読まれます。中身が x = 1 の random.py と、random.randint(1, 6) を呼ぶ main.py を置きました。3.15.2・3.14.7 では次の文です(<dir> には実際のフォルダが出ます)。

AttributeError: module 'random' has no attribute 'randint' (consider renaming '<dir>\random.py' since it has the same name as the standard library module named 'random' and prevents importing that standard library module)

下の表では、この括弧を「consider renaming(標準)」と書きます。numpy.py などで出る (consider renaming '<dir>\numpy.py' if it has the same name as a library you intended to import) は「consider renaming(library)」です。

ファイルの構成3.15.2・3.14.73.12.10
random.py+main.pyconsider renaming(標準)ヒントなし
random.py の中で import randomconsider renaming(標準)partially initialized module 'random' has no attribute 'randint' (most likely due to a circular import)(csv では 'csv'・'reader')
csv.py の中で import csvconsider renaming(標準)
空の json.py+main.pyconsider renaming(標準)ヒントなし
空の numpy.py+main.pymodule 'numpy' has no attribute 'array'(ヒントなし)
numpy.py・pandas.py の中で自分を importconsider renaming(library)(3.14.7 だけ実行)未実行
  • 3.13 以降は consider renaming のヒントが出ます(What's New 3.13。3.13 そのものは未実行)。
  • 標準ライブラリ以外の名前は、そのファイルの読み込み途中で属性を探したときだけヒントが出ました(自分の中で import した・下の循環 import。今回の実測の範囲)。

直し方:ファイル名を変える

自作ファイルを my_random.py のように重ならない名前に変え、もう一度実行して同じ AttributeError が消えたか確かめます。NumPy 入りの環境でも同じ表示だったので、入れ直しでは直りません。No module named は別の原因で、ModuleNotFoundError の解説や VS Code での切り分けを見てください。

partially initialized module(循環 import)

a.py(import b の後で def hello())と b.py(import a → a.hello())を、main.py から import a しました。

版最終行
3.15.2・3.14.7module 'a' has no attribute 'hello'+consider renaming(library)
3.12.10partially initialized module 'a' has no attribute 'hello' (most likely due to a circular import)

from a import f の形では ImportError: cannot import name 'f' になりました。3.12.10 だけは partially initialized module ... circular import の文です。

今回の例では、3.15.2・3.14.7 の文に circular import と出ませんでした。ただし、3.12 と同じ文が残る循環 import もあるとコア開発者が説明しています(gh-136094)。consider renaming と出ても名前がライブラリと重ならないなら、ファイル同士が import し合っていないか確かめます。共通の関数を3つ目のファイルに移すなど、お互いを import しない形にします(この直し方のコードは試していません)。

7. 自作クラスの AttributeError

書いたコード最終行(3版同じ)
self.name を作って u.nmae'User' object has no attribute 'nmae'
__init__ で count = 0(self. なし)'Counter' object has no attribute 'count'
メソッドの字下げがずれてクラスの外'A' object has no attribute 'show'
クラスそのものに A.missingtype object 'A' has no attribute 'missing'

インスタンスに持たせる値は self. を付けて作ります(クラスの基本)。字下げのずれは、def を class の中まで下げて直します。

class Counter:
    def __init__(self):
        self.count = 0      # self. を付ける
    def up(self):
        self.count += 1
        return self.count

print(Counter().up())       # 1

8. 属性を設定できない:no __dict__・no setter

= で代入したときに出ます。3.13 から説明が付きました(gh-96663・3.13.0a1 の NEWS)。

コード3.15.2・3.14.73.12.10
__slots__ = ('x',) で p.y = 1'P' object has no attribute 'y' and no __dict__ for setting new attributesand no ... なし
object().x = 1・'abc'.x = 1同じく and no __dict__ ... 付きand no ... なし
setter の無い property に代入property 'v' of 'C' object has no setter

__slots__ のクラスは並べた名前しか持てず、str などにも属性を足せません。property に代入するなら @v.setter を足します。

class C:
    def __init__(self):
        self._v = 1
    @property
    def v(self):
        return self._v
    @v.setter
    def v(self, value):
        self._v = value

c = C()
c.v = 2
print(c.v)   # 2

9. pandas・NumPy で消えたメソッド

3.14.7 で出した最終行です。

コード最終行代わり
df.append({'a': 2}, ignore_index=True)'DataFrame' object has no attribute 'append'pd.concat()(2.0.0 で削除)
df.ix[0]... no attribute 'ix'loc・iloc(1.0.0 で削除)
df.iteritems()... 'iteritems'. Did you mean: 'isetitem'?df.items()(2.0.0 で削除)
pd.Series(['a b']).split()'Series' ... 'split'. Did you mean: 'plot'?s.str.split()
列 price があって df.prise... 'prise'. Did you mean: 'price'?ヒントの列名
np.float(1)module 'numpy' has no attribute 'float'.+説明float・np.float64(1.24.0 で削除)
np.array([1, 2]).append(3)'numpy.ndarray' object has no attribute 'append'np.append(a, 3)

pandas で出るヒントは外れることがあります。iteritems に isetitem、split に plot が出ましたが、正しい代わりは items() と .str.split() です。

np.float は例外の行の後に代わりの説明が続き、最終行は URL でした。np.int・np.object も同じ形です。

df = pd.DataFrame({"a": [1]})
df = pd.concat([df, pd.DataFrame([{"a": 2}])], ignore_index=True)
print(df["a"].tolist(), df.loc[0, "a"], df.iloc[1, 0])   # [1, 2] 1 2

a = np.array([1, 2])
print(np.append(a, 3).tolist())   # [1, 2, 3](新しい配列が返る)

import pandas as pd・import numpy as np の後に書く断片です。3.15.2 では pandas・NumPy を試していません。

10. よくある質問(FAQ)

Q. 'NoneType' object has no attribute とはどういう意味ですか?

値が None なので、そのメソッドは使えないという意味です。sort() の戻り値の代入、return 忘れ、re.match() の不一致で出ました。

Q. NumPy を入れ直しても module 'numpy' has no attribute 'array' が消えません。

同じフォルダに自作の numpy.py がないか確かめてください。別の main.py から読んだときは、3.15.2・3.14.7 でもヒントが出ませんでした。

Q. Did you mean のヒントが出ないのはなぜですか?

似た名前が見つからないと出ません。IPython など独自に表示する画面では出ないことがあると What's New 3.10 にあります。

本記事は、生成AIを活用して下書きし、運営者が内容を確認・編集したうえで公開しています。AIの利用方針は免責事項をご覧ください。

11. まとめ

  • 最初の引用符の型を見る。'NoneType' なら None を入れた行を探す
  • 正しい名前なのに module 'x' と出たら、同じフォルダの自作 x.py を疑う
  • pandas・NumPy の古い名前は pd.concat()・.items()・float に置き換える

直ったら次はこちら。

📌
参考にした一次情報と検証環境(2026年11月27日実測)

AttributeError/What's New 3.10・3.13(Python 公式)、CPython の gh-144285・gh-146406・gh-136094・gh-96663、pandas・NumPy のリリースノート。実測環境は1章の囲みのとおりです。