{"id":122586,"date":"2020-12-27T07:55:57","date_gmt":"2020-12-27T07:55:57","guid":{"rendered":"https:\/\/blog.finxter.com\/?p=19606"},"modified":"2020-12-27T07:55:57","modified_gmt":"2020-12-27T07:55:57","slug":"python-getattr","status":"publish","type":"post","link":"https:\/\/sickgaming.net\/blog\/2020\/12\/27\/python-getattr\/","title":{"rendered":"Python getattr()"},"content":{"rendered":"<p class=\"has-pale-cyan-blue-background-color has-background\">Python&#8217;s built-in <code>getattr(object, string)<\/code> function returns the value of the <code>object<\/code>&#8216;s attribute with name <code>string<\/code>. If this doesn&#8217;t exist, it returns the value provided as an optional third <code>default<\/code> argument. If that doesn&#8217;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>\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-large\"><img decoding=\"async\" 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\/uploads\/2020\/12\/getattr-1-300x169.jpg 300w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/12\/getattr-1-768x432.jpg 768w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/12\/getattr-1-150x84.jpg 150w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><\/figure>\n<\/div>\n<h2>Usage<\/h2>\n<p>Learn by example! Here&#8217;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>\n<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\nclass Car: def __init__(self, brand, speed): self.brand = brand self.speed = speed # Create object\nporsche = Car('porsche', 100)\ntesla = Car('tesla', 110) # Two alternatives to get instance attributes:\nprint(getattr(porsche, 'brand') + \" \" + str(getattr(porsche, 'speed')))\nprint(tesla.brand + \" \" + str(tesla.speed)) # Get an attribute that doesn't exist with default argument:\nprint(getattr(porsche, 'color', 'red'))\n<\/pre>\n<p>The output of this code snippet is:<\/p>\n<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\ntesla 110\nred<\/pre>\n<h2>Syntax getattr()<\/h2>\n<p>The <code>getattr()<\/code> object has the following syntax: <\/p>\n<pre class=\"wp-block-preformatted\"><strong>Syntax: <\/strong>\n<code><strong>getattr(object, attribute[, default])<\/strong> # Get object's attribute value or default if non-existent<\/code><\/pre>\n<figure class=\"wp-block-table is-style-stripes\">\n<table>\n<tbody>\n<tr>\n<td><strong>Arguments<\/strong><\/td>\n<td><code>object<\/code><\/td>\n<td>The object from which the attribute value should be drawn.<\/td>\n<\/tr>\n<tr>\n<td><\/td>\n<td><code>attribute<\/code><\/td>\n<td>The attribute name as a string.<\/td>\n<\/tr>\n<tr>\n<td><\/td>\n<td><code>default<\/code><\/td>\n<td>The return value in case the attribute doesn&#8217;t exist.<\/td>\n<\/tr>\n<tr>\n<td><strong>Return Value<\/strong><\/td>\n<td><code>object<\/code><\/td>\n<td>Returns the value of the <code>attribute<\/code> of instance <code>object<\/code> or <code>default<\/code> if non-existent.<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<\/figure>\n<h2>Video getattr()<\/h2>\n<figure class=\"wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio\">\n<div class=\"wp-block-embed__wrapper\">\n<div class=\"ast-oembed-container\"><iframe loading=\"lazy\" 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>\n<\/div>\n<\/figure>\n<h2>Return value from getattr()<\/h2>\n<p>The <code>getattr(object, attribute, default)<\/code> method returns one of the following:<\/p>\n<ul>\n<li>the value of the <code>object<\/code>&#8216;s <code>attribute <\/code><\/li>\n<li><code>default<\/code>, if the attribute doesn&#8217;t exist<\/li>\n<li><code>AttributeError<\/code> if neither the attribute exists, nor <code>default<\/code> is provided.<\/li>\n<\/ul>\n<h2>Interactive Shell Exercise: Understanding getattr()<\/h2>\n<p>Consider the following interactive code:<\/p>\n<p> <iframe loading=\"lazy\" src=\"https:\/\/trinket.io\/embed\/python\/48f2b083eb\" marginwidth=\"0\" marginheight=\"0\" allowfullscreen=\"\" width=\"100%\" height=\"356\" frameborder=\"0\"><\/iframe> <\/p>\n<p><em><strong>Exercise<\/strong>: <\/em>Fix the error in the code!<\/p>\n<hr class=\"wp-block-separator\"\/>\n<p><strong>But before we move on, I&#8217;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>\n<p>If you like one-liners, you&#8217;ll LOVE the book. It&#8217;ll teach you everything there is to know about a <strong>single line of Python code.<\/strong> But it&#8217;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>\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter\"><a href=\"https:\/\/amzn.to\/2WAYeJE\" target=\"_blank\" rel=\"noopener noreferrer\"><img decoding=\"async\" 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>\n<\/div>\n<p>The book is released in 2020 with the world-class programming book publisher NoStarch Press (San Francisco). <\/p>\n<p>Link: <a href=\"https:\/\/nostarch.com\/pythononeliners\" target=\"_blank\" rel=\"noreferrer noopener\">https:\/\/nostarch.com\/pythononeliners<\/a><\/p>\n<hr class=\"wp-block-separator\"\/>\n<h2>Why Using getattr() Instead of Dot to Get an Attribute?<\/h2>\n<p>You&#8217;ve seen two alternatives to get an attribute: <\/p>\n<ul>\n<li><code>getattr(object, attribute_str)<\/code><\/li>\n<li><code>object.attribute<\/code><\/li>\n<\/ul>\n<p>Why using the getattr() function over the more concise dot syntax?<\/p>\n<p>There are two main reasons:<\/p>\n<ul>\n<li><code>getattr()<\/code> provides a default value in case the attribute doesn&#8217;t exist whereas the dot syntax throws an error. <\/li>\n<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>\n<\/ul>\n<h2>Related Functions<\/h2>\n<ul>\n<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>\n<li>The <code>hasattr()<\/code> function checks if an attribute exists.<\/li>\n<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>\n<\/ul>\n<h2>Summary<\/h2>\n<p>Python&#8217;s built-in <code>getattr(object, string)<\/code> function returns the value of the <code>object<\/code>&#8216;s attribute with name <code>string<\/code>. <\/p>\n<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\nclass Car: def __init__(self, brand, speed): self.brand = brand self.speed = speed porsche = Car('porsche', 100)\nprint(getattr(porsche, 'brand') + \" \" + str(getattr(porsche, 'speed')))\n# porsche 100<\/pre>\n<p>If this doesn&#8217;t exist, it returns the value provided as an optional third <code>default<\/code> argument. <\/p>\n<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'))\n# red<\/pre>\n<p>If that doesn&#8217;t exist either, it raises an <code>AttributeError<\/code>. <\/p>\n<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')) '''\nTraceback (most recent call last): File \"C:\\Users\\xcent\\Desktop\\Finxter\\Blog\\HowToConvertBooleanToStringPython\\code.py\", line 12, in &lt;module> print(getattr(porsche, 'color'))\nAttributeError: 'Car' object has no attribute 'color' '''<\/pre>\n<p>An example is <code>getattr(porsche, 'speed')<\/code> which is equivalent to <code>porsche.speed<\/code>.<\/p>\n<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'))\nprint(porsche.speed)\n# Both print attribute value: 100<\/pre>\n<hr class=\"wp-block-separator\"\/>\n<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>\n<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>\n<h2>Where to Go From Here?<\/h2>\n<p>Enough theory, let\u2019s get some practice!<\/p>\n<p>To become successful in coding, you need to get out there and solve real problems for real people. That\u2019s how you can become a six-figure earner easily. And that\u2019s how you polish the skills you really need in practice. After all, what\u2019s the use of learning theory that nobody ever needs?<\/p>\n<p><strong>Practice projects is how you sharpen your saw in coding!<\/strong><\/p>\n<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>\n<p>Then become a Python freelance developer! It\u2019s the best way of approaching the task of improving your Python skills\u2014even if you are a complete beginner.<\/p>\n<p>Join my free webinar <a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/webinar-freelancer\/\" target=\"_blank\">\u201cHow to Build Your High-Income Skill Python\u201d<\/a> and watch how I grew my coding business online and how you can, too\u2014from the comfort of your own home.<\/p>\n<p><a href=\"https:\/\/blog.finxter.com\/webinar-freelancer\/\" target=\"_blank\" rel=\"noreferrer noopener\">Join the free webinar now!<\/a><\/p>\n<\/p>\n<\/p>\n<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>\n","protected":false},"excerpt":{"rendered":"<p>Python&#8217;s built-in getattr(object, string) function returns the value of the object&#8216;s attribute with name string. If this doesn&#8217;t exist, it returns the value provided as an optional third default argument. If that doesn&#8217;t exist either, it raises an AttributeError. An example is getattr(porsche, &#8216;speed&#8217;) which is equivalent to porsche.speed. Usage Learn by example! Here&#8217;s an [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[857],"tags":[73,468,528],"class_list":["post-122586","post","type-post","status-publish","format-standard","hentry","category-python-tut","tag-programming","tag-python","tag-tutorial"],"_links":{"self":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/122586","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/comments?post=122586"}],"version-history":[{"count":0,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/122586\/revisions"}],"wp:attachment":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/media?parent=122586"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/categories?post=122586"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/tags?post=122586"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}