09-04-2020, 05:14 PM
How to Access an Object Attribute Given the Attribute Name as a String?
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 because the dot notation only allows for name-access like this: . 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:
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 method which returns a string representation of the weapon.
The Getattr() Function
As mentioned above, the function allows you to access the class object attribute. Its syntax is , the first two parameters are required, and the third is optional.
Output:
You first create a class object. Second, you get its caliber and color. Since your object does not have an attribute called , 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:
https://repl.it/@finxter/sadfds?lite=true
Exercise: Change the output to also print the name of the object.
The Hasattr() Function
The function checks if the attribute exists and prints out the bool value: if so or if it does not exist. This function has only two parameters that need to be specified: object and attribute.
Output:
As we can see, the function checked whether our object named has the attributes we included in the listand returned and values to us. This function is especially useful when we have written many lines of code and our projectis huge, then we can quickly and easily check if an object has some attribute or even several attributes.
The Setattr() Function
The function sets an attribute. Moreover, if the attribute does not exist, it will be created. There are three parameters, and all are required:
Output:
As you can see, the function fulfilled its role. At the beginning, we checked if the attribute named exists and at that time it did not exist yet (), then we set the value for this attribute and as we can see, after using , the object obtained a new attribute ().
The Delattr() Function
The function deletes a given attribute from a specific object. Just like with , the parameters are two – object and attribute.
Output:
At first, we created a Gun class object and a list with attribute names. Later we checked if the object has these attributes (, ), then we used in thefor loop and checked again (, ).
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:
Output:
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 function.
You can delete an attribute using thefunction:
Output:
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 function and the loop.
Summary
We started with an explanation of what the attributes in Python are, and then the functions, , and 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.
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
Code:
object."attribute"Code:
object.attributeQuick Solution: There are four ways to access the object attribute in Python via the built-in functions:
- — provides access to the object attribute,Code:
getattr()
- — checks whether an attribute exists or not,Code:
hasattr()
- — is used for setting an attribute, if the attribute does not exist, it will be created,Code:
setattr()
- — deletes the attribute.Code:
delattr()
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
Code:
get_entryCode:
class Gun: def __init__(self, name, caliber): self.name = name self.caliber = caliberAs mentioned above, the
Code:
getattr()Code:
getattr(object, attribute, default)- 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.
Code:
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:
Code:
7,62 mm
the attribute named color does not existYou first create a
Code:
GunCode:
colorYou can run this code in our interactive Python shell:
https://repl.it/@finxter/sadfds?lite=true
Exercise: Change the output to also print the name of the object.
The Hasattr() Function
The
Code:
hasattr()Code:
TrueCode:
FalseCode:
attributes = ['name', 'color', 'caliber', 'designer'] for attribute in attributes: print(hasattr(ak47, attribute))Output:
Code:
True
False
True
FalseAs we can see, the
Code:
hasattr()Code:
ak47Code:
TrueCode:
FalseThe Setattr() Function
The
Code:
setattr()- object – object of your class,
- attribute – name of the attribute you want to set,
- value – the value you want to give to the attribute.
Code:
ak47 = Gun('ak47', '7,62 mm') print(hasattr(ak47, 'mass'))
setattr(ak47, 'mass', '3.47 kg')
print(hasattr(ak47, 'mass'))Output:
Code:
False
TrueAs you can see, the function fulfilled its role. At the beginning, we checked if the attribute named
Code:
massCode:
FalseCode:
setattr()Code:
TrueThe Delattr() Function
The
Code:
delattr()Code:
hasattr()Code:
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:
Code:
True
True
***
False
FalseAt first, we created a Gun class object and a list with attribute names. Later we checked if the object has these attributes (
Code:
TrueCode:
TrueCode:
delattr()Code:
FalseCode:
FalseOther 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:
Code:
ak47 = Gun('ak-47', '7,62 mm')
print(ak47.caliber) print(ak47.name)
ak47.name = 'ak-74'
print(ak47.name)Output:
Code:
7,62 mm
ak-47
ak-74This 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
Code:
getattr()You can delete an attribute using the
Code:
delCode:
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:
Code:
True
True
***
False
FalseAs 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
Code:
delattr()Code:
forSummary
We started with an explanation of what the attributes in Python are, and then the functions
Code:
getattr()Code:
hasattr()Code:
setattr()Code:
delattr()I hope this article has answered all your questions about how to access an object attribute.

