Python AttributeError
The code tries to access an attribute or method that doesn't exist on an object.
Explanation
AttributeError occurs when you try to access an attribute or call a method on an object that doesn't have that attribute. For example, calling .append() on a tuple, accessing .name on an object that doesn't have it, or calling a method that doesn't exist. This is different from NameError which is about undefined variables - AttributeError is about objects that exist but don't have the requested attribute.
Common Causes
- Method name typo
- Object type doesn't have the attribute
- Attribute not initialized in __init__
- Using wrong object type
- Attribute removed or renamed
Solution
Check the object's type using type() or isinstance() to verify it has the expected attribute. Use hasattr(obj, 'attr') to check before accessing. Use getattr(obj, 'attr', default) to access with a default value. Verify method names for typos. Check the documentation for the library/class you're using. Use dir(obj) to list all available attributes. For custom classes, ensure __init__() properly initializes all attributes.
Code Example
# AttributeError on wrong method name
my_list = [1, 2, 3]
my_list.appned(4) # AttributeError: 'list' has no attribute 'appned'
# Fix
my_list.append(4)
# Accessing non-existent attribute
class User:
def __init__(self, name):
self.name = name
user = User("John")
print(user.email) # AttributeError: 'User' has no attribute 'email'
# Fix: add attribute
class User:
def __init__(self, name, email=None):
self.name = name
self.email = email
# Safe access with getattr
email = getattr(user, 'email', 'not provided')
# Wrong type - tuple doesn't have append
data = (1, 2, 3)
data.append(4) # AttributeError: 'tuple' has no attribute 'append'
# Fix: use list
data = [1, 2, 3]
data.append(4)
Error Information
Language
python
Difficulty
Beginner
Views
118
Related Errors
Python
Python ValueError
A function received an argument of correct type but inappropriate value.
Python
Python SyntaxError
Python detected invalid syntax in the source code.
Python
Python RuntimeWarning: coroutine was never awaited
An async coroutine was created but never awaited, so it never executed.
Python
Python KeyError
The code tries to access a dictionary key that doesn't exist.