![]() |
|
[Tut] How to Access an Object Attribute Given the Attribute Name as a String? - Printable Version +- Sick Gaming (https://sickgaming.net) +-- Forum: Programming (https://sickgaming.net/forum-76.html) +--- Forum: Python (https://sickgaming.net/forum-83.html) +--- Thread: [Tut] How to Access an Object Attribute Given the Attribute Name as a String? (/thread-97046.html) |
[Tut] How to Access an Object Attribute Given the Attribute Name as a String? - xSicKxBot - 09-04-2020 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 Code: object."attribute"Code: object.attributeQuick 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 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)
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()
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. |