[Solved]: AttributeError in Python


In Python, AttributeError is sub class of Exception. AttributeError occurred when an attribute reference or assignment fails because pointing object does not support attribute references or attribute assignment.

Example AttributeError

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 Python program is throwing AttributeError in line 6 because attribute q is not declared inside the class Test but trying to print through program that’s why Python throw 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.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s