python エラー「AttributeError: ‘xxx’ object has no attribute ‘xxx’」が発生した場合の対処法

python エラー「AttributeError: ‘xxx’ object has no attribute ‘xxx’」が発生した場合の対処法

pythonで、エラー「AttributeError: ‘xxx’ object has no attribute ‘xxx’」が発生した場合の対処法を記述してます。存在しないプロパティやメソッドを使用した際に発生します。pythonのバージョンは3.10.0を使用してます。

環境

  • OS windows11 home 64bit
  • python 3.10.0

エラー全文

以下のコードで発生。
※その他のエラーは後述してます。

class Human:
    def __init__(self):
        self.name = "hoge"
        self.age = 10
        self.address = "Tokyo"

human = Human()

print(human.name) # hoge
print(human.weight)

エラー全文

    print(human.weight)
AttributeError: 'Human' object has no attribute 'weight'

原因

存在しないプロパティを指定しているため

対処法

存在するプロパティを指定するか、プロパティを追加する

class Human:
    def __init__(self):
        self.name = "hoge"
        self.age = 10
        self.address = "Tokyo"
        self.weight = 65

human = Human()

print(human.name) # hoge
print(human.weight) # 65

「try」~「except」しておけば「AttributeError」をキャッチできます。

class Human:
    def __init__(self):
        self.name = "hoge"
        self.age = 10
        self.address = "Tokyo"

human = Human()

try:
    print(human.name) # hoge
    print(human.weight)

except AttributeError:
    print("AttributeErrorが発生")

その他のエラー

定義してないメソッドを指定

定義してないメソッドを指定しても発生します。

s = "hello"
s.sort()

AttributeError: 'str' object has no attribute 'sort'

文字列をソートする場合は、以下の2つの方法で可能です。

s = "hello"

print("".join(sorted(s))) # ehllo

print(sorted(s)) # ['e', 'h', 'l', 'l', 'o']

重複した名称のファイルを使用

また、同じ階層に「numpy.py」などという名前のファイルがあった場合などにも発生します。

import numpy as  np

arr = np.array([1.0, 2.0, 3.0, 4.0, 5.0])

AttributeError: module 'numpy' has no attribute 'array'

importした「numpy」が、同じ階層にある「numpy.py」と判断されるためエラーとなります。

スペルミス

メソッドのスペルミスなどでも発生します。以下の場合は「search」が「serch」になっているため発生してます。

import re

str1 = "he22o"

print(bool(re.serch(r'\d', str1))) # True

Traceback (most recent call last):
  File "C:\sample\test.py", line 8, in <module>
    print(bool(re.serch(r'\d', str1))) # True
AttributeError: module 're' has no attribute 'serch'. Did you mean: 'search'?