How to fix object has no attribute [Python is easy]

When you try to use attributes that do not exist in the object you get an error and your program failed. In order to avoid this, you can use getattr(obj, attr_name, default_value) function or a try-except construction. The first case the most preferable because you can set a default value that returns if the attribute does not exist

Class for testing and example print for existing attributes.

    class Human:
        def __init__(self, name, height):
            self.name = name
            self.height = height

    human = Human(name='Bob', height=187)

    print(f"Name: {human.name}; Height: {human.height}")

Output:

Name: Bob; Height: 187

Using getattr() function.

    print(f"Gender: {getattr(human, 'gender', 'male')}")

Output:

Gender: male

Using try-except construction.

    try:
        print(human.gender)
    except AttributeError as e:
        print(e)

    print("Program finished.")

Output:

'Human' object has no attribute 'gender'
Program finished.

#python
0
Roman Ivashchenko profile picture
Nov 10, 2020
by Roman Ivashchenko
Did it help you?
Yes !
No

Best related