【Python】AttributeError

AttributeError

AttributeErrorとは、属性(Attribute)を呼び出す際に発生するエラーです。(※属性(Attribute)とは、オブジェクトに存在する変数やメソッドのこと)

AttributeErrorが発生した場合は、オブジェクト名、識別子名は正しいかどうか確認しましょう。具体的には、標準関数dir()を用いると、そのオブジェクトが対象の変数やオブジェクト(つまり属性)を持ち合わせているか確認出来ます。 

AttributeError の例

a = 10
a.append(20)

エラー内容

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'int' object has no attribute 'append'

上記の変数aには、append()という属性を持ち合わせていないため、AttributeErrorが発生しています。dir()を用いると一覧を確認出来ます。

print(dir(a))

出力結果

['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__init_subclass__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes']

上記のように変数aにはappend()が定義されていません。append()はリスト型で利用できるメソッドですので、以下のようにすれば解決出来ます。

a = [10]
a.append(20)
print(a)

出力結果

[10, 20]

Pythonを効率よく学ぶには?

Pythonを効率よく学ぶには、現役のデータサイエンティストや機械学習エンジニアに質問ができる環境で学ぶことです。

AI Academy Bootcampでは、体系的に学べる動画コンテンツに加え、現役の機械学習エンジニアやデータサイエンティストに受講期間中質問し放題、コードレビューし放題の環境で学べます。

オンラインで学べるので、好きな時間に勉強できます。
受講料も6ヶ月間35,000円で学べます。

コスパ良くPythonやAIスキルを身に付けたい方は、AI Academy Bootcampの受講ご検討ください。

コメントを残す