Code Fix

中級AttributeError: 'NoneType' object has no attribute の原因と直し方 › パターン2

AttributeError: 'NoneType' object has no attribute の原因と直し方

Noneに対してメソッドを呼び出したときに出るエラーです。

 1  def find(items, target):
 2      for i in items:
 3          if i == target:
 4              return i
 5  
 6  value = find([1, 2, 3], __)
                             ^
 7  print(value.real)
Traceback (most recent call last): File "main.py", line 7, in <module> print(value.real) ^^^^^^^^^^ AttributeError: 'NoneType' object has no attribute 'real'

空欄を埋めて実行を通す

広告
広告スロット(未設定)

AttributeError: 'NoneType' object has no attribute の原因と直し方

関数が値を見つけられずNoneを返す場面や、辞書のgetでキーが無かった場合に起きやすいパターンです。

このエラーの解説と類題をまとめて見る →

広告
広告スロット(未設定)