You may know the following problem: You have an object’s attribute name as a string—say, you’ve read it from a file—and you want to access the attribute with the given name. But you cannot use the syntax object."attribute"
because the dot notation only allows for name-access like this: object.attribute
. How do you resolve this problem? This article will show you how!
Quick Solution: There are four ways to access the object attribute in Python via the built-in functions:
getattr()
— provides access to the object attribute,hasattr()
— checks whether an attribute exists or not,setattr()
— is used for setting an attribute, if the attribute does not exist, it will be created,delattr()
— deletes the attribute.
What Are Attributes Anyways?
We call attribute everything is contained inside an object in Python. There is no real distinguishing between plain data and functions—both are objects. Thus, everything you’ll learn about attributes also applies to methods.
In this article, I will use the following class to show how to access the attributes. It represents a gun of some name and its caliber. In addition, it provides a get_entry
method which returns a string representation of the weapon.
class Gun: def __init__(self, name, caliber): self.name = name self.caliber = caliber
The Getattr() Function
As mentioned above, the getattr()
function allows you to access the class object attribute. Its syntax is getattr(object, attribute, default)
, the first two parameters are required, and the third is optional.
- object β an object of the class which has been created,
- attribute β the name of the attribute from which you want to get the value,
- default β message that will be printed out if the attribute does not exist.
ak47 = Gun(name='Ak-47', caliber='7,62 mm') print(getattr(ak47, 'caliber', f'the attribute named {"caliber"} does not exist')) print(getattr(ak47, 'color', f'the attribute named {"color"} does not exist'))
Output:
7,62 mm the attribute named color does not exist
You first create a Gun
class object. Second, you get its caliber and color. Since your object does not have an attribute called color
, you only received its caliber and information that the attribute named color does not exist.
You can run this code in our interactive Python shell:
Exercise: Change the output to also print the name of the object.
The Hasattr() Function
The hasattr()
function checks if the attribute exists and prints out the bool value: True
if so or False
if it does not exist. This function has only two parameters that need to be specified: object and attribute.
attributes = ['name', 'color', 'caliber', 'designer'] for attribute in attributes: print(hasattr(ak47, attribute))
Output:
True False True False
As we can see, the hasattr()
function checked whether our object named ak47
has the attributes we included in the list and returned True
and False
values to us. This function is especially useful when we have written many lines of code and our project is huge, then we can quickly and easily check if an object has some attribute or even several attributes.
The Setattr() Function
The setattr()
function sets an attribute. Moreover, if the attribute does not exist, it will be created. There are three parameters, and all are required:
- object – object of your class,
- attribute – name of the attribute you want to set,
- value – the value you want to give to the attribute.
ak47 = Gun('ak47', '7,62 mm') print(hasattr(ak47, 'mass')) setattr(ak47, 'mass', '3.47 kg') print(hasattr(ak47, 'mass'))
Output:
False True
As you can see, the function fulfilled its role. At the beginning, we checked if the attribute named mass
exists and at that time it did not exist yet (False
), then we set the value for this attribute and as we can see, after using setattr()
, the object obtained a new attribute (True
).
The Delattr() Function
The delattr()
function deletes a given attribute from a specific object. Just like with hasattr()
, the parameters are two – object and attribute.
ak47 = Gun('ak47', '7,62 mm') attributes = ['name', 'caliber'] for attribute in attributes: print(hasattr(ak47, attribute)) for attribute in attributes: delattr(ak47, attribute) print('***') for attribute in attributes: print(hasattr(ak47, attribute))
Output:
True True *** False False
At first, we created a Gun class object and a list with attribute names. Later we checked if the object has these attributes (True
, True
), then we used delattr()
in the for loop and checked again (False
, False
).
Other Methods To Access Object Attribute:
Finally, you must also provide another way to check/change the value of the attribute or delete the attribute completely.
You can also access the attribute using dotted-syntax:
ak47 = Gun('ak-47', '7,62 mm') print(ak47.caliber) print(ak47.name) ak47.name = 'ak-74' print(ak47.name)
Output:
7,62 mm ak-47 ak-74
This way it also works, but remember that it can cause Error when a given attribute does not exist (this cannot be prevented as easily as with the built-in functions) and additionally we can’t check the value of several objects at once using the loop, so we have to use the getattr()
function.
You can delete an attribute using the del
function:
ak47 = Gun('ak47', '7,62 mm') attributes = ['name', 'caliber'] for attribute in attributes: print(hasattr(ak47, attribute)) del ak47.name del ak47.caliber print('***') for attribute in attributes: print(hasattr(ak47, attribute))
Output:
True True *** False False
As we can see, we have managed to delete, but we have to call the attributes one by one, so if we want to delete more attributes, it is better to use the delattr()
function and the for
loop.
Summary
We started with an explanation of what the attributes in Python are, and then the functions getattr()
, hasattr()
, setattr()
and delattr()
were described. Finally, we presented other methods with the help of which you can see/change the value of an attribute and also remove an attribute completely.
I hope this article has answered all your questions about how to access an object attribute.