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 | PIL Attributes PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. Attributes: Attribute defines the various property of an object, element or file. In the image, attribute refers to the size, filename, format or mode, etc. of the image. Image used is: Instances
2 min read
Dynamic Attributes in Python Dynamic attributes in Python are terminologies for attributes that are defined at runtime, after creating the objects or instances. In Python we call all functions, methods also as an object. So you can define a dynamic instance attribute for nearly anything in Python. Consider the below example for
2 min read
Python delattr() Function In Python, the delattr() function is used to delete an attribute from an object. In this article, we will learn about the Python delattr() function. Python delattr() Syntaxdelattr (object, name) Parameters: Object: An object from which we want to delete the attribute name: The name of the attribute
3 min read
Python | getattr() method The getattr() method in Python returns the value of a named attribute of an object. If the attribute is not found then it returns the default value provided. If no default is given and the attribute does not exist then it raises an AttributeError.Python getattr() Method SyntaxSyntax : getattr(obj, k
3 min read
Python hasattr() method Python hasattr() function is an inbuilt utility function, which is used to check if an object has the given named attribute and return true if present, else false. In this article, we will see how to check if an object has an attribute in Python. Syntax of hasattr() function Syntax : hasattr(obj, ke
2 min read
How to Print Object Attributes in Python In Python, objects are the cornerstone of its object-oriented programming paradigm. An object is an instance of a class, and it encapsulates both data (attributes) and behaviors (methods). Understanding how to access and print the attributes of an object is fundamental for debugging, inspecting, and
2 min read
How to Change Class Attributes in Python In Python, editing class attributes involves modifying the characteristics or properties associated with a class. Class attributes are shared by all instances of the class and play an important role in defining the behavior and state of objects within the class. In this article, we will explore diff
3 min read
Dataframe Attributes in Python Pandas In this article, we will discuss the different attributes of a dataframe. Attributes are the properties of a DataFrame that can be used to fetch data or any information related to a particular dataframe. The syntax of writing an attribute is: DataFrame_name.attribute These are the attributes of the
11 min read
How to Access dict Attribute in Python In Python, A dictionary is a type of data structure that may be used to hold collections of key-value pairs. A dictionary's keys are connected with specific values, and you can access these values by using the keys. When working with dictionaries, accessing dictionary attributes is a basic function
6 min read
Accessing Attributes and Methods in Python In Python, attributes and methods define an object's behavior and encapsulate data within a class. Attributes represent the properties or characteristics of an object, while methods define the actions or behaviors that an object can perform. Understanding how to access and manipulate both attributes
3 min read