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?

<div><p><em><strong>You may know the following problem:</strong> 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> because the dot notation only allows for name-access like this: <code>object.attribute</code>. How do you resolve this problem? This article will show you how! </em></p>
<p><strong>Quick Solution: </strong>There are four ways to access the object attribute in Python via the built-in functions:</p>
<ul>
<li><code>getattr()</code> — provides access to the <a href="https://blog.finxter.com/python-attributes/" target="_blank" rel="noreferrer noopener" title="Class and Instance Attributes in Python — Every Coder Must Know the Difference! [+Video Guide]">object attribute</a>,</li>
<li><code>hasattr()</code>— checks whether an attribute exists or not,</li>
<li><code>setattr()</code>— is used for setting an attribute, if the attribute does not exist, it will be created,</li>
<li><code>delattr()</code>— deletes the attribute.</li>
</ul>
<h2>What Are Attributes Anyways?</h2>
<p>We call<em> </em><strong><em>attribute</em></strong><em> </em>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.</p>
<p>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_entry</code> method which returns a string representation of the weapon.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">class Gun: def __init__(self, name, caliber): self.name = name self.caliber = caliber</pre>
<h2>The Getattr() Function</h2>
<p>As mentioned above, the <code>getattr()</code> function allows you to access the class object attribute. Its syntax is <code>getattr(object, attribute, default)</code>, the first two parameters are required, and the third is optional.</p>
<ul>
<li><strong>object </strong>– an object of the class which has been created,</li>
<li><strong>attribute</strong> – the name of the attribute from which you want to get the value,</li>
<li><strong>default</strong> – message that will be printed out if the attribute does not exist.</li>
</ul>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">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'))</pre>
<p>Output:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">7,62 mm
the attribute named color does not exist</pre>
<p>You first create a <code>Gun</code> class object. Second, you get its caliber and color. Since your object does not have an attribute called <code>color</code>, you only received its caliber and information that <em>the attribute named color does not exist</em>.</p>
<p>You can run this code in our interactive Python shell:</p>
<p> <iframe height="600px" width="100%" src="https://repl.it/@finxter/sadfds?lite=true" scrolling="no" frameborder="no" allowtransparency="true" allowfullscreen="true" sandbox="allow-forms allow-pointer-lock allow-popups allow-same-origin allow-scripts allow-modals"></iframe> </p>
<p><em><strong>Exercise</strong>: Change the output to also print the name of the object. </em></p>
<h2>The Hasattr() Function</h2>
<p>The <code>hasattr()</code> function checks if the attribute exists and prints out the bool value: <code>True</code> if so or <code>False</code> if it does not exist. This function has only two parameters that need to be specified: object and attribute.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">attributes = ['name', 'color', 'caliber', 'designer'] for attribute in attributes: print(hasattr(ak47, attribute))</pre>
<p>Output:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">True
False
True
False</pre>
<p>As we can see, the <code>hasattr()</code> function checked whether our object named <code>ak47</code> has the attributes we included in the <a href="https://blog.finxter.com/python-lists/" target="_blank" rel="noreferrer noopener" title="The Ultimate Guide to Python Lists">list </a>and returned <code>True</code> and <code>False</code> values to us. This function is especially useful when we have written many lines of code and our <a href="https://blog.finxter.com/how-real-freelancers-earn-money-in-2019-10-practical-python-projects/" target="_blank" rel="noreferrer noopener" title="How Real Freelancers Earn Money in 2020: 10 Practical Python Projects">project </a>is huge, then we can quickly and easily check if an object has some attribute or even several attributes.</p>
<h2>The Setattr() Function</h2>
<p>The <code>setattr()</code> function sets an attribute. Moreover, if the attribute does not exist, it will be created. There are three parameters, and all are required:</p>
<ul>
<li><strong>object </strong>– object of your class,</li>
<li><strong>attribute</strong> – name of the attribute you want to set,</li>
<li><strong>value</strong> – the value you want to give to the attribute.</li>
</ul>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">ak47 = Gun('ak47', '7,62 mm') print(hasattr(ak47, 'mass'))
setattr(ak47, 'mass', '3.47 kg')
print(hasattr(ak47, 'mass'))</pre>
<p>Output:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">False
True</pre>
<p>As you can see, the function fulfilled its role. At the beginning, we checked if the attribute named <code>mass</code> exists and at that time it did not exist yet (<code>False</code>), then we set the value for this attribute and as we can see, after using <code>setattr()</code>, the object obtained a new attribute (<code>True</code>).</p>
<h2>The Delattr() Function</h2>
<p>The <code>delattr()</code> function deletes a given attribute from a specific object. Just like with <code>hasattr()</code>, the parameters are two – object and attribute.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">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))</pre>
<p>Output:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">True
True
***
False
False</pre>
<p>At first, we created a Gun class object and a list with attribute names. Later we checked if the object has these attributes (<code>True</code>, <code>True</code>), then we used <code>delattr()</code> in the<a href="https://blog.finxter.com/python-one-line-for-loop-a-simple-tutorial/" title="Python One Line For Loop [A Simple Tutorial]" target="_blank" rel="noreferrer noopener"> for loop</a> and checked again (<code>False</code>, <code>False</code>).</p>
<h2>Other Methods To Access Object Attribute:</h2>
<p>Finally, you must also provide another way to check/change the value of the attribute or delete the attribute completely.</p>
<p>You can also access the attribute using dotted-syntax:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">ak47 = Gun('ak-47', '7,62 mm')
print(ak47.caliber) print(ak47.name)
ak47.name = 'ak-74'
print(ak47.name)</pre>
<p>Output:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">7,62 mm
ak-47
ak-74</pre>
<p>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 <a href="https://blog.finxter.com/python-loops/" title="Python Loops" target="_blank" rel="noreferrer noopener">loop</a>, so we have to use the <code>getattr()</code> function.</p>
<p>You can delete an attribute using the <a href="https://blog.finxter.com/how-to-remove-items-from-a-list-while-iterating/" target="_blank" rel="noreferrer noopener" title="How To Remove Items From A List While Iterating?"><code>del</code> </a>function:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">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))</pre>
<p>Output:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">True
True
***
False
False</pre>
<p>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 <code>delattr()</code> function and the<code> for</code> loop.</p>
<h2>Summary</h2>
<p>We started with an explanation of what the attributes in Python are, and then the functions <code>getattr()</code>, <code>hasattr()</code>, <code>setattr()</code> and <code>delattr()</code> 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. </p>
<p>I hope this article has answered all your questions about how to access an object attribute.</p>
</div>


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



Forum Jump:


Users browsing this thread:
1 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016