What are attributes?
Attributes refers to all the variables and methods associated with a particular class or object. They are essentially the data and functionality that make up an object or class.
We use the dot notation to access, set or modify an attribute. For example:
class Example:
a = 200
#access attributes from the class
print(Example.a)
#Access attributes from instances
e = Example()
print(e.a)
#Set new attribute in an object
e.b = 300
print(e.b)
Note: We can also use the getattr() and the setattr() builtin functions to access and set attributes respectively.
class Example:
a = 200
#access attributes using the getattr function
print(getattr(Example, 'a'))
#set attributes using the setattr function
setattr(Example, "b", 500) #Equivalent to Example.b = 500
print(getattr(Example, 'b'))
When is AttributeError raised?
AttributeError
exception occurs when an attribute reference or assignment fails.This exception is typically raised when we try to access a non-existent attribute of an object.
class Example:
a = 100
e = Example()
print(e.a)
print(e.b) #Raises an attribute error
class Example:
a = 100
e = Example()
print(getattr(Example, "a"))
print(getattr(Example, "b")) #Raises an attribute error
The attribute error is also common when using builtin data types. For example, the list
data type defines the sort()
method, we might assume that equally, tuple or dictionary would also have a sort()
method. However, attempting to call this method on a dictionary or tuple will raise the AttributeError
exception.
L = [5, 9, 3, 7, 1]
L.sort()
print(L)
T = (5, 9, 3, 7, 1)
T.sort()#Raises an attribute Error
Common causes of AttributeError exception
- Calling an attribute that doesn't exist.
- Using a wrong spelling or syntax on an attribute.
- Trying to access an attribute that has not been initialized.
- Accessing unbound attributes:
- Passing an incorrect argument to a function or method.
- Trying to access a class variable outside of a class.
Avoiding and Fixing AttributeError exceptions
The most obvious way to avoid AttributeError
, is making sure that we are using the correct attribute names. We should also check if the attribute we are trying to access exists in the object.
In cases where we are uncertain if an attribute exists, for example when we are accessing the attributes dynamically from user inputs; We can use the getattr() function which allows us to set a custom default to be returned instead of raising the AttributError
.
getattr(obj, name, default = None)
class Example:
a = 100
print(getattr(Example, "a"))
#set a custom default value
print(getattr(Example, "b", "Nonexistent attribute!"))
We can also use the try-except
blocks to catch the exception and then proceed accordingly.
class Example:
a = "Python"
try:
print(Example.a)
print(Example.b)
except AttributeError as e:
print("Nonexistent attribute!")