AttributeError: 'str' object has no attribute
AttributeError: 'str' object has no attribute in Python means you called a method or read an attribute that this kind of object does not have: a list method on a string, a typo, or an attribute your own class never stored.
How do I fix AttributeError: 'str' object has no attribute?
AttributeError: 'str' object has no attribute means you used a method this type does not have. Common causes are a list method on a string, such as word.reverse(), a typo like uppercase() for upper(), or a JSON string you never parsed. Print type(obj) and use a method that type has.
- 1. Check the real typePrint type(obj) before the failing line. A str where you expected a list or dict is the usual surprise.
- 2. List what it supportsPrint dir(obj) to see valid method names. Fix typos such as uppercase() to upper().
- 3. Your own classFor 'Student' object has no attribute 'name', make sure __init__ sets self.name = name, not name = name.
What does AttributeError: 'str' object has no attribute mean?
Each object has only the attributes of its type. 'str' object has no attribute 'reverse' means reverse exists (on lists), just not on strings. With your own class, 'Student' object has no attribute 'name' usually means __init__ never stored it on self. (When the type is 'NoneType', the value was None: that has its own guide.)
Why does AttributeError: 'str' object has no attribute happen?
1. A method that belongs to a different type
Strings, lists and dicts each have their own methods.
Breaks
word.reverse() # lists have reverse(), strings do notWorks
word[::-1]2. An attribute never stored in __init__
name = name only sets a local variable that disappears when __init__ returns.
Breaks
def __init__(self, name):
name = nameWorks
def __init__(self, name):
self.name = name3. A typo or the wrong name
Python does not guess; uppercase is not upper.
Breaks
text.uppercase()Works
text.upper()4. Text where you expected parsed data
A JSON response is a string until you parse it.
Breaks
data = response_text
data.get("id")Works
data = json.loads(response_text)
data.get("id")How to find it in your own code
Print type(obj) and dir(obj) just before the failing line: the first shows which object you really have, the second lists what it supports. For your own class, check that every attribute is assigned to self.<name> in __init__.
Try it: fix this bug
easygreet_student("Asha") crashes: AttributeError: 'Student' object has no attribute 'name'.
class Student:
def __init__(self, name):
name = name
def greeting(self):
return "Hi, " + self.name
def greet_student(name):
return Student(name).greeting()More challenges with this error
Each of these challenges runs into this error. Find the bug and fix it, no install and no account needed.
Still not sure why yours breaks?
Paste it into the visualizer and watch it run line by line, with every variable at every step. Free, and it runs in your browser.