In every programming language, if we develop new programs, there is a high chance of getting errors or exceptions. These errors yield to the program not being executed. One of the error in Python mostly occurs is "AttributeError". AttributeError can be defined as an error that is raised when an attribute reference or assignment fails.
For example, if we take a variable x we are assigned a value of 10. In this process suppose we want to append another value to that variable. It's not possible. Because the variable is an integer type it does not support the append method. So in this type of problem, we get an error called "AttributeError". Suppose if the variable is list type then it supports the append method. Then there is no problem and not getting"Attribute error".
Note: Attribute errors in Python are generally raised when an invalid attribute reference is made.
There are a few chances of getting AttributeError.
Example 1:
Python3
# Python program to demonstrate
# AttributeError
X = 10
# Raises an AttributeError
X.append(6)
Output:
Traceback (most recent call last):
File "/home/46576cfdd7cb1db75480a8653e2115cc.py", line 5, in
X.append(6)
AttributeError: 'int' object has no attribute 'append'
Example 2: Sometimes any variation in spelling will cause an Attribute error as Python is a case-sensitive language.
Python3
# Python program to demonstrate
# AttributeError
# Raises an AttributeError as there is no
# method as fst for strings
string = "The famous website is { }".fst("geeksforgeeks")
print(string)
Output:
Traceback (most recent call last):
File "/home/2078367df38257e2ec3aead22841c153.py", line 3, in
string = "The famous website is { }".fst("geeksforgeeks")
AttributeError: 'str' object has no attribute 'fst'
Example 3: AttributeError can also be raised for a user-defined class when the user tries to make an invalid attribute reference.
Python3
# Python program to demonstrate
# AttributeError
class Geeks():
def __init__(self):
self.a = 'GeeksforGeeks'
# Driver's code
obj = Geeks()
print(obj.a)
# Raises an AttributeError as there
# is no attribute b
print(obj.b)
Output:
GeeksforGeeks
Error:
Traceback (most recent call last):
File "/home/373989a62f52a8b91cb2d3300f411083.py", line 17, in
print(obj.b)
AttributeError: 'Geeks' object has no attribute 'b'
Example 4: AttributeError can also be raised for a user-defined class when the user misses out on adding tabs or spaces between their lines of code.
Python3
#This is a dictionary parsing code written by Amit Jadhav
#Because of an Indentation Error you will experience Attribute Error
class dict_parsing:
def __init__(self,a):
self.a = a
def getkeys(self):
if self.notdict():
return list(self.a.keys())
def getvalues(self):
if self.notdict():
return list(self.a.values())
def notdict(self):
if type(self.a) != dict:
raise Exception(self,a,'not a dictionary')
return 1
def userinput(self):
self.a = eval(input())
print(self.a,type(self.a))
print(self.getykeys())
print(self.getvalyes())
def insertion(self,k,v):
self.a[k]=v
d = dict_parsing({"k1":"amit", "k2":[1,2,3,4,5]})
d.getkeys()
Output:
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-9-c26cd169473f> in <module>
----> 1 d.getkeys()
AttributeError: 'dict_parsing' object has no attribute 'getkeys'
Error:
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-9-c26cd169473f> in <module>
----> 1 d.getkeys()
AttributeError: 'dict_parsing' object has no attribute 'getkeys'
Solution for AttributeError
Errors and exceptions in Python can be handled using exception handling i.e. by using try and except in Python.
Example: Consider the above class example, we want to do something else rather than printing the traceback Whenever an AttributeError is raised.
Python3
# Python program to demonstrate
# AttributeError
class Geeks():
def __init__(self):
self.a = 'GeeksforGeeks'
# Driver's code
obj = Geeks()
# Try and except statement for
# Exception handling
try:
print(obj.a)
# Raises an AttributeError
print(obj.b)
# Prints the below statement
# whenever an AttributeError is
# raised
except AttributeError:
print("There is no such attribute")
Output:
GeeksforGeeks
There is no such attribute
Note: To know more about exception handling click here.
Similar Reads
Python Tutorial | Learn Python Programming Language Python Tutorial â Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly.Python is:A high-level language, used in web development, data science, automatio
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Python Data Types Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read