Attribute error occurs in python when we try to assign an attribute value to a python objects or class instance in which that particular attribute does not exist. In other word when the python compiler not able to find defined data or attribute on an object which allow for attribute references, it throws the "AttributeError".
Error Code Example:
welcome = "Hello World {}".formats("Stechies")
print(welcome)
Output:
Traceback (most recent call last):
File "t.py", line 1, in <module>
welcome = "Hello World {}".formats("Stechies")
AttributeError: 'str' object has no attribute 'formats'
We are getting this error because we have assigned format() functions as formats(). While compiling the code python compiler search for the specific format of function and throws the ‘Attribute Error’.
Correct Code:
welcome = "Hello World {}".format("Stechies")
print(welcome)
Output:
Hello World Stechies
Error Code 2:
str = " STechies "
print("String with Strip: " + str.sstrip())
Output:
Traceback (most recent call last):
File "t.py", line 7, in <module>
print("String with Strip: " + str.sstrip())
AttributeError: 'str' object has no attribute 'sstrip'
In the above example we have assigned strip() function as sstrip() which causes the error.
Explanation:
This type of error occur when we try to join two different function, method or objects with DOT operator (.) or miss-spell.
Correction for Error Code 2:
str = " STechies "
print("String with Strip: " + str.strip())
Output:
String with Strip: STechies