Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] Python getattr()

#1
Python getattr()

<div><p class="has-pale-cyan-blue-background-color has-background">Python’s built-in <code>getattr(object, string)</code> function returns the value of the <code>object</code>‘s attribute with name <code>string</code>. If this doesn’t exist, it returns the value provided as an optional third <code>default</code> argument. If that doesn’t exist either, it raises an <code>AttributeError</code>. An example is <code>getattr(porsche, 'speed')</code> which is equivalent to <code>porsche.speed</code>. </p>
<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" width="1024" height="576" src="https://blog.finxter.com/wp-content/uploads/2020/12/getattr-1-1024x576.jpg" alt="How to get an attribute with getattr() in Python - Illustrated Guide" class="wp-image-19612" srcset="https://blog.finxter.com/wp-content/uploads/2020/12/getattr-1-scaled.jpg 1024w, https://blog.finxter.com/wp-content/uplo...00x169.jpg 300w, https://blog.finxter.com/wp-content/uplo...68x432.jpg 768w, https://blog.finxter.com/wp-content/uplo...150x84.jpg 150w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>
</div>
<h2>Usage</h2>
<p>Learn by example! Here’s an example on how to use the <code>getattr()</code> <a href="https://blog.finxter.com/python-built-in-functions/" title="Python Built-In Functions">built-in function</a>.</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=""># Define class with one attribute
class Car: def __init__(self, brand, speed): self.brand = brand self.speed = speed # Create object
porsche = Car('porsche', 100)
tesla = Car('tesla', 110) # Two alternatives to get instance attributes:
print(getattr(porsche, 'brand') + " " + str(getattr(porsche, 'speed')))
print(tesla.brand + " " + str(tesla.speed)) # Get an attribute that doesn't exist with default argument:
print(getattr(porsche, 'color', 'red'))
</pre>
<p>The output of this code snippet is:</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="">porsche 100
tesla 110
red</pre>
<h2>Syntax getattr()</h2>
<p>The <code>getattr()</code> object has the following syntax: </p>
<pre class="wp-block-preformatted"><strong>Syntax: </strong>
<code><strong>getattr(object, attribute[, default])</strong> # Get object's attribute value or default if non-existent</code></pre>
<figure class="wp-block-table is-style-stripes">
<table>
<tbody>
<tr>
<td><strong>Arguments</strong></td>
<td><code>object</code></td>
<td>The object from which the attribute value should be drawn.</td>
</tr>
<tr>
<td></td>
<td><code>attribute</code></td>
<td>The attribute name as a string.</td>
</tr>
<tr>
<td></td>
<td><code>default</code></td>
<td>The return value in case the attribute doesn’t exist.</td>
</tr>
<tr>
<td><strong>Return Value</strong></td>
<td><code>object</code></td>
<td>Returns the value of the <code>attribute</code> of instance <code>object</code> or <code>default</code> if non-existent.</td>
</tr>
</tbody>
</table>
</figure>
<h2>Video getattr()</h2>
<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio">
<div class="wp-block-embed__wrapper">
<div class="ast-oembed-container"><iframe title="Python getattr() - Ultimate Guide" width="1400" height="788" src="https://www.youtube.com/embed/5MXDZI3jRio?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></div>
</div>
</figure>
<h2>Return value from getattr()</h2>
<p>The <code>getattr(object, attribute, default)</code> method returns one of the following:</p>
<ul>
<li>the value of the <code>object</code>‘s <code>attribute </code></li>
<li><code>default</code>, if the attribute doesn’t exist</li>
<li><code>AttributeError</code> if neither the attribute exists, nor <code>default</code> is provided.</li>
</ul>
<h2>Interactive Shell Exercise: Understanding getattr()</h2>
<p>Consider the following interactive code:</p>
<p> <iframe src="https://trinket.io/embed/python/48f2b083eb" marginwidth="0" marginheight="0" allowfullscreen="" width="100%" height="356" frameborder="0"></iframe> </p>
<p><em><strong>Exercise</strong>: </em>Fix the error in the code!</p>
<hr class="wp-block-separator"/>
<p><strong>But before we move on, I’m excited to present you my brand-new Python book <a rel="noreferrer noopener" href="https://amzn.to/2WAYeJE" target="_blank" title="https://amzn.to/2WAYeJE">Python One-Liners</a></strong> (Amazon Link).</p>
<p>If you like one-liners, you’ll LOVE the book. It’ll teach you everything there is to know about a <strong>single line of Python code.</strong> But it’s also an <strong>introduction to computer science</strong>, data science, machine learning, and algorithms. <strong><em>The universe in a single line of Python!</em></strong></p>
<div class="wp-block-image">
<figure class="aligncenter"><a href="https://amzn.to/2WAYeJE" target="_blank" rel="noopener noreferrer"><img loading="lazy" width="215" height="283" src="https://blog.finxter.com/wp-content/uploads/2020/02/image-1.png" alt="" class="wp-image-5969"/></a></figure>
</div>
<p>The book is released in 2020 with the world-class programming book publisher NoStarch Press (San Francisco). </p>
<p>Link: <a href="https://nostarch.com/pythononeliners" target="_blank" rel="noreferrer noopener">https://nostarch.com/pythononeliners</a></p>
<hr class="wp-block-separator"/>
<h2>Why Using getattr() Instead of Dot to Get an Attribute?</h2>
<p>You’ve seen two alternatives to get an attribute: </p>
<ul>
<li><code>getattr(object, attribute_str)</code></li>
<li><code>object.attribute</code></li>
</ul>
<p>Why using the getattr() function over the more concise dot syntax?</p>
<p>There are two main reasons:</p>
<ul>
<li><code>getattr()</code> provides a default value in case the attribute doesn’t exist whereas the dot syntax throws an error. </li>
<li><code>getattr()</code> allows to dynamically access the attribute with the string instead of the name. For example, you may obtain the string as a user input, in which case, you cannot use the dot syntax <code>object.attribute</code> because <code>attribute</code> is a string, not a name.</li>
</ul>
<h2>Related Functions</h2>
<ul>
<li>The <code><a href="https://blog.finxter.com/python-setattr/" target="_blank" rel="noreferrer noopener" title="Python setattr()">setattr()</a></code> function returns the value of an attribute.</li>
<li>The <code>hasattr()</code> function checks if an attribute exists.</li>
<li>The <code><a href="https://blog.finxter.com/python-delattr/" target="_blank" rel="noreferrer noopener" title="Python delattr()">delattr()</a></code> function deletes an existing attribute.</li>
</ul>
<h2>Summary</h2>
<p>Python’s built-in <code>getattr(object, string)</code> function returns the value of the <code>object</code>‘s attribute with name <code>string</code>. </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=""># Define class with one attribute
class Car: def __init__(self, brand, speed): self.brand = brand self.speed = speed porsche = Car('porsche', 100)
print(getattr(porsche, 'brand') + " " + str(getattr(porsche, 'speed')))
# porsche 100</pre>
<p>If this doesn’t exist, it returns the value provided as an optional third <code>default</code> argument. </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="">print(getattr(porsche, 'color', 'red'))
# red</pre>
<p>If that doesn’t exist either, it raises an <code>AttributeError</code>. </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="">print(getattr(porsche, 'color')) '''
Traceback (most recent call last): File "C:\Users\xcent\Desktop\Finxter\Blog\HowToConvertBooleanToStringPython\code.py", line 12, in &lt;module> print(getattr(porsche, 'color'))
AttributeError: 'Car' object has no attribute 'color' '''</pre>
<p>An example is <code>getattr(porsche, 'speed')</code> which is equivalent to <code>porsche.speed</code>.</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="">print(getattr(porsche, 'speed'))
print(porsche.speed)
# Both print attribute value: 100</pre>
<hr class="wp-block-separator"/>
<p>I hope you enjoyed the article! To improve your Python education, you may want to join the popular free <a href="https://blog.finxter.com/email-academy/" target="_blank" rel="noreferrer noopener" title="Email Academy">Finxter Email Academy</a>:</p>
<p>Do you want to boost your Python skills in a fun and easy-to-consume way? Consider the following resources and become a master coder!</p>
<h2>Where to Go From Here?</h2>
<p>Enough theory, let’s get some practice!</p>
<p>To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?</p>
<p><strong>Practice projects is how you sharpen your saw in coding!</strong></p>
<p>Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?</p>
<p>Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.</p>
<p>Join my free webinar <a rel="noreferrer noopener" href="https://blog.finxter.com/webinar-freelancer/" target="_blank">“How to Build Your High-Income Skill Python”</a> and watch how I grew my coding business online and how you can, too—from the comfort of your own home.</p>
<p><a href="https://blog.finxter.com/webinar-freelancer/" target="_blank" rel="noreferrer noopener">Join the free webinar now!</a></p>
</p>
</p>
<p>The post <a href="https://blog.finxter.com/python-getattr/" target="_blank" rel="noopener noreferrer">Python getattr()</a> first appeared on <a href="https://blog.finxter.com/" target="_blank" rel="noopener noreferrer">Finxter</a>.</p>
</div>


https://www.sickgaming.net/blog/2020/12/...n-getattr/
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016