An AttributeError is raised in Python when you try to access or call an attribute (a property or method) that does not exist on an object. This typically means the object is not the type you expected, or the attribute was never defined.
Why it happens
- •Accessing an attribute that was never defined in __init__ or the class body.
- •Calling a method that does not exist on that particular type (e.g. .sort() on a tuple).
- •A variable holds None instead of the expected object.
- •Typo in the attribute name.
Examples
Code that triggers the error
class User:
def __init__(self, name):
self.name = name
user = User("Alice")
print(user.email)Error output
Traceback (most recent call last):
File "app.py", line 6, in <module>
print(user.email)
AttributeError: 'User' object has no attribute 'email'How to fix it
Use hasattr(obj, 'attr') or getattr(obj, 'attr', default) to check safely. Make sure all attributes are initialized in __init__. If the variable might be None, add a None check before accessing any attributes.
Fixed code
class User:
def __init__(self, name, email=None):
self.name = name
self.email = email
user = User("Alice", email="alice@example.com")
print(user.email) # alice@example.com
# Or check first:
print(getattr(user, "email", "not set"))Related errors
Ready to practice your English at work?
Lingua-e has interactive exercises built around real developer conversations: standups, code reviews, retrospectives, and more. Practice until it comes naturally.
Try Lingua-e for free