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.
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)
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.
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')
'Test' object has no attribute 'q' This is an example of AttributeError exception
In this topic you learn about the case when the AttributeError occurred in Python program and way to handle this error through exception handling.