MeWrite Docs

AttributeError: 'NoneType' object has no attribute

オブジェクトに存在しない属性やメソッドにアクセスした場合に発生するエラー

概要

AttributeError は、オブジェクトに存在しない属性やメソッドにアクセスしようとした場合に発生するエラーです。特に 'NoneType' object has no attribute は、None に対してメソッドを呼び出そうとした場合に発生します。

エラーメッセージ

Traceback (most recent call last):
  File "script.py", line 5, in <module>
    result.lower()
AttributeError: 'NoneType' object has no attribute 'lower'
AttributeError: 'str' object has no attribute 'append'
AttributeError: module 'json' has no attribute 'load'

原因

  1. None に対するメソッド呼び出し: 関数が None を返した
  2. 型の間違い: 文字列にリストのメソッドを使用など
  3. スペルミス: メソッド名や属性名の誤り
  4. モジュールの誤用: モジュールと同名のファイル
  5. 初期化されていない変数: 変数が適切に設定されていない

解決策

1. None チェック

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
# ❌ None の可能性がある
result = some_function()
print(result.lower())

# ✅ None チェックを追加
result = some_function()
if result is not None:
    print(result.lower())

# ✅ or でデフォルト値
result = some_function() or ""
print(result.lower())

2. 関数の戻り値を確認

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
# ❌ list.sort() は None を返す
data = [3, 1, 2]
sorted_data = data.sort()  # sorted_data は None
print(sorted_data.index(1))  # AttributeError

# ✅ in-place 変更を理解
data = [3, 1, 2]
data.sort()  # data 自体が変更される
print(data.index(1))

# ✅ sorted() は新しいリストを返す
data = [3, 1, 2]
sorted_data = sorted(data)
print(sorted_data.index(1))

3. 正しいメソッドを使用

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
# ❌ 文字列に append はない
text = "Hello"
text.append(" World")

# ✅ 文字列の連結
text = "Hello"
text = text + " World"
# または
text = f"{text} World"

# ❌ リストに lower はない
items = ["A", "B", "C"]
items.lower()

# ✅ 各要素を変換
items = [item.lower() for item in items]

4. hasattr() で属性確認

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class User:
    def __init__(self, name):
        self.name = name

user = User("Alice")

# ❌ 存在しない属性
print(user.email)

# ✅ hasattr() で確認
if hasattr(user, "email"):
    print(user.email)
else:
    print("No email")

# ✅ getattr() でデフォルト値
email = getattr(user, "email", "unknown")

5. モジュール名の衝突を解消

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
# ❌ json.py というファイルがあると衝突
# json.py の中で
import json
json.loads("{}")  # AttributeError

# ✅ ファイル名を変更
# my_json_parser.py に名前変更

# 確認方法
import json
print(json.__file__)  # 読み込まれているモジュールのパス

6. 辞書アクセスと属性アクセスの違い

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
# 辞書はドット記法でアクセスできない
data = {"name": "Alice", "age": 30}

# ❌ AttributeError
print(data.name)

# ✅ ブラケット記法
print(data["name"])

# ✅ SimpleNamespace で属性アクセス
from types import SimpleNamespace
data = SimpleNamespace(name="Alice", age=30)
print(data.name)

7. クラスメソッドとインスタンスメソッド

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class MyClass:
    @classmethod
    def class_method(cls):
        pass

    def instance_method(self):
        pass

# ❌ クラスからインスタンスメソッドを呼び出し
MyClass.instance_method()

# ✅ インスタンスから呼び出し
obj = MyClass()
obj.instance_method()

# ✅ クラスメソッドはクラスから呼び出し可能
MyClass.class_method()

8. 正規表現のマッチ結果

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
import re

text = "No match here"
match = re.search(r"\d+", text)

# ❌ マッチしない場合は None
print(match.group())  # AttributeError

# ✅ マッチ結果を確認
if match:
    print(match.group())
else:
    print("No match")

9. BeautifulSoup での要素検索

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
from bs4 import BeautifulSoup

html = "<html><body><p>Hello</p></body></html>"
soup = BeautifulSoup(html, "html.parser")

# ❌ 要素が見つからない場合 None
element = soup.find("div")
print(element.text)  # AttributeError

# ✅ 存在確認
element = soup.find("div")
if element:
    print(element.text)
else:
    print("Element not found")

デバッグのコツ

型の確認

1
2
3
result = some_function()
print(type(result))  # <class 'NoneType'> など
print(dir(result))   # 利用可能な属性一覧

条件分岐でのデバッグ

1
2
3
4
result = some_function()
if result is None:
    print("Function returned None")
    # 原因を調査

Python の他のエラー

最終更新: 2025-12-08