Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] How to Access an Object Attribute Given the Attribute Name as a String?

#1
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 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.



https://www.sickgaming.net/blog/2020/09/...-a-string/
Reply



Possibly Related Threads…
Thread Author Replies Views Last Post
  [Tut] How To Format A String That Contains Curly Braces In Python? xSicKxBot 0 30 09-25-2020, 07:51 PM
Last Post: xSicKxBot
  [Tut] How to Solve Python “TypeError: ‘int’ object is not iterable”? xSicKxBot 0 36 09-18-2020, 01:49 PM
Last Post: xSicKxBot
  [Tut] The Most Pythonic Way to Convert a List to a String xSicKxBot 0 88 06-21-2020, 01:35 PM
Last Post: xSicKxBot
  [Tut] string.join(list) vs list.join(string) | Why Python’s Creators Chose The Former xSicKxBot 0 118 06-19-2020, 05:12 AM
Last Post: xSicKxBot
  [Tut] The Most Pythonic Way to Convert a List of Tuples to a String xSicKxBot 0 87 06-09-2020, 12:22 AM
Last Post: xSicKxBot
  [Tut] Python List to String: A Helpful Guide with Interactive Shell xSicKxBot 0 175 04-18-2020, 08:55 PM
Last Post: xSicKxBot

Forum Jump:

Become a Patron!
[-]
Upcoming Events

[-]
Latest Threads
PlanetSide 2 External Hack / Mod
Last Post: FarCry10
Today 05:27 PM
» Replies: 6
» Views: 6811
(Indie Deal) FREE Defense of Roman Brita...
Last Post: xSicKxBot
Today 03:53 PM
» Replies: 0
» Views: 1
AppleInsider - Lowest iPad Pro prices: s...
Last Post: xSicKxBot
Today 03:19 PM
» Replies: 0
» Views: 1
Microsoft - CVP Tom McGuinness: Top take...
Last Post: xSicKxBot
Today 03:19 PM
» Replies: 0
» Views: 1
News - Nintendo First Revealed The Switc...
Last Post: xSicKxBot
Today 03:19 PM
» Replies: 0
» Views: 1
News - Luigi Can Be Unlocked As A Secret...
Last Post: xSicKxBot
Today 03:19 PM
» Replies: 0
» Views: 1
Xbox Wire - Announcing Details for Xbox ...
Last Post: xSicKxBot
Today 01:19 PM
» Replies: 0
» Views: 2
News - Report: China-owned mobile studio...
Last Post: xSicKxBot
Today 01:19 PM
» Replies: 0
» Views: 3
News - Get a job: Join Insomniac Games a...
Last Post: xSicKxBot
Today 01:19 PM
» Replies: 0
» Views: 3
Microsoft - The importance of bringing b...
Last Post: xSicKxBot
Today 08:18 AM
» Replies: 0
» Views: 4

[-]
Twitter

[-]
Sponsored
Get the Deal of the Week at RefurBees.com

Copyright © SickGaming.net 2012-2020