Python AttributeError is sub class of Exception. Python AttributeError occurred when an attribute reference or assignment fails because pointing object does not support attribute references or attribute assignment.
See Also:
Python AttributeError Example
In this Python program, Test class is having attribute p and initialize with 0 inside the constructor __init__().
class Test:
def __init__(self):
self.p = 0
f = Test()
print(f.p)
print(f.q)
Output
print(f.q)
AttributeError: 'Test' object has no attribute 'q'
This program is throwing Python AttributeError in line 6 because attribute q is not declared inside the class Test but trying to print through program that’s why throw Python AttributeError.
Solution
To solve this problem you can handle exception in program by using try and except block.
try:
class Test:
def __init__(self):
self.p = 0
f = Test()
print(f.p)
print(f.q)
except Exception as e:
print (e)
print ('This is an example of StandardError exception')
Output
'Test' object has no attribute 'q'
This is an example of AttributeError exception
Conclusion
In this topic you learn about the case when the AttributeError occurred in Python program and way to handle this error through exception handling.
Related Posts
Your Feedback Motivate Us
If our FacingIssuesOnIT Experts solutions guide you to resolve your issues and improve your knowledge. Please share your comments, like and subscribe to get notifications for our posts.
Happy Learning !!!
You must log in to post a comment.