{"id":2003,"date":"2019-12-30T17:32:58","date_gmt":"2019-12-30T17:32:58","guid":{"rendered":"https:\/\/www.askpython.com\/?p=2003"},"modified":"2023-02-16T19:57:20","modified_gmt":"2023-02-16T19:57:20","slug":"python-setattr-function","status":"publish","type":"post","link":"https:\/\/www.askpython.com\/python\/python-setattr-function","title":{"rendered":"Python setattr() Function"},"content":{"rendered":"\n<p>Python <code>setattr()<\/code> function is used to set the attribute of an object, given its name. While being a very simple function, it can prove to be very useful in the context of <a href=\"https:\/\/www.askpython.com\/python\/oops\/object-oriented-programming-python\" class=\"rank-math-link\">Object Oriented Programming in Python<\/a>. Let us look at how we could use this function in our Python programs.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-text-color has-background has-vivid-green-cyan-background-color has-vivid-green-cyan-color\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">setattr() Function Syntax<\/h2>\n\n\n\n<p>It takes the object name, the attribute name and the value as the parameters, and sets <code>object.attribute<\/code> to be equal to <code>value<\/code>. Since any object attribute can be of any type, no exception is raised by this function.<\/p>\n\n\n\n<p><strong>Format<\/strong>: <code>setattr(object, attr, value)<\/code><\/p>\n\n\n\n<p>Here is a simple example to demonstrate the use of <code>setattr()<\/code>.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nclass MyClass():\n    def __init__(self, name, value):\n        # Set the attribute of the class object\n        setattr(self, name, value)\n\na = MyClass(&#039;KEY&#039;, 100)\nprint(&#039;Printing attribute from Class Object:&#039;, a.KEY)\nprint(&#039;Printing attribute from getattr():&#039;, getattr(a, &#039;KEY&#039;))\n<\/pre><\/div>\n\n\n<p><strong>Output<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nPrinting attribute from Class Object: 100\nPrinting attribute from getattr(): 100\n<\/pre><\/div>\n\n\n<p><code>setattr()<\/code> is very useful when the attribute of the object is not know beforehand, and cannot be set using <code>object.attribute_name = value<\/code>.<\/p>\n\n\n\n<p>This is a very handy method, used whenever the attributes of the object can change during runtime, and demonstrates how Object Oriented Programming still performs well in these scenarios.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-text-color has-background has-vivid-green-cyan-background-color has-vivid-green-cyan-color\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Using setattr() with getattrr()<\/h2>\n\n\n\n<p>It is commonly used in tandem with the <code>getattr()<\/code> method, to get and set the attributes of Objects.<\/p>\n\n\n\n<p>Here is an example to demonstrate some of the use-cases of <code>setattr()<\/code>, when paired with the <code>getattr()<\/code> method.<\/p>\n\n\n\n<p>This example constructs objects and sets the attributes of each subject to their corresponding marks, for a single student.<\/p>\n\n\n\n<p>After constructing the Student object using <code>setattr()<\/code>, we use <code>getattr()<\/code> and sort the subject-wise marks of students.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nclass Student():\n\tdef __init__(self, name, results):\n\t\tself.name = name\n\t\tfor key, value in results.items():\n                        # Sets the attribute of the &#039;subject&#039; to\n                        # the corresponding subject mark.\n                        # For example: a.&#039;Chemistry&#039; = 75\n\t\t\tsetattr(self, key, value)\n\n\tdef update_mark(self, subject, mark):\n\t\tself.subject = mark\n\n\nsubjects = &#x5B;&#039;Physics&#039;, &#039;Chemistry&#039;, &#039;Biology&#039;]\n\na = Student(&#039;Amit&#039;, {key: value for (key, value) in zip(subjects, &#x5B;73, 81, 90])})\n\nb = Student(&#039;Rahul&#039;, {key: value for (key, value) in zip(subjects, &#x5B;91, 89, 74])})\n\nc = Student(&#039;Sunil&#039;, {key: value for (key, value) in zip(subjects, &#x5B;59, 96, 76])})\n\nstudent_list = &#x5B;a, b, c]\n\nstud_names = &#x5B;student.name for student in student_list]\n\nprint(&#039;Sorted Physics Marks:&#039;)\nprint(sorted(&#x5B;getattr(s, &#039;Physics&#039;) for s in student_list]))\n\nprint(&#039;\\nSorted Marks for all subjects:&#039;)\nprint(sorted(&#x5B;getattr(s, subject) for s in student_list for subject in subjects]))\n\nprint(&#039;\\nSorted Marks for every Student:&#039;)\nprint(dict(zip(stud_names, &#x5B;sorted(&#x5B;getattr(s, subject) for subject in subjects]) for s in student_list])))\n<\/pre><\/div>\n\n\n<p>While some of the Python one-liners may seem very complicated, it is not. The first one <code>sorted([getattr(s, 'Physics') for s in student_list])<\/code> is equivalent to:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nls = &#x5B;]\nfor s in student_list:\n    ls.append(getattr(s, &#039;Physics&#039;))\n# Sort the list\nls.sort()\nprint(ls)\n<\/pre><\/div>\n\n\n<p>The second one liner is also extremely similar, but using two nested loops instead of one.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nls = &#x5B;]\nfor s in student_list:\n    for subject in subjects:\n        ls.append(getattr(s, subject))\nls.sort()\nprint(ls)\n<\/pre><\/div>\n\n\n<p>The last one is a bit tricky, wherein you construct a Dictionary of <code>name: sorted_subject_marks<\/code> for each student.<\/p>\n\n\n\n<p>We first iterate through each name and get the attribute from the student object list, and then sort the intermediate list, before adding to our Dictionary.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\ndct = {}\nfor name, s in zip(subjects, student_list):\n    ls = &#x5B;]\n    for subject in subjects:\n        ls.append(getattr(s, subject))\n    ls.sort()\n    dct&#x5B;name] = ls\nprint(dct)\n<\/pre><\/div>\n\n\n<p>Output of the complete code snippet:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nSorted Physics Marks:\n&#x5B;59, 73, 91]\n\nSorted Marks for all subjects:\n&#x5B;59, 73, 74, 76, 81, 89, 90, 91, 96]\n\nSorted Marks for every Student:\n{&#039;Amit&#039;: &#x5B;73, 81, 90], &#039;Rahul&#039;: &#x5B;74, 89, 91], &#039;Sunil&#039;: &#x5B;59, 76, 96]}\n<\/pre><\/div>\n\n\n<hr class=\"wp-block-separator has-text-color has-background has-vivid-green-cyan-background-color has-vivid-green-cyan-color\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Conclusion<\/h2>\n\n\n\n<p>In this article, we learned about the <code>setattr()<\/code> method, which is used to dynamically set the object attributes at runtime. This is a very useful method for Object Oriented Programming, when the attributes are not known to the developer, and is thus used for building flexible API.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">References<\/h2>\n\n\n\n<ul class=\"wp-block-list\"><li><a class=\"rank-math-link rank-math-link\" href=\"https:\/\/python-reference.readthedocs.io\/en\/latest\/docs\/functions\/setattr.html\" target=\"_blank\" rel=\"noopener\">Python Docs<\/a><\/li><\/ul>\n","protected":false},"excerpt":{"rendered":"<p>Python setattr() function is used to set the attribute of an object, given its name. While being a very simple function, it can prove to be very useful in the context of Object Oriented Programming in Python. Let us look at how we could use this function in our Python programs. setattr() Function Syntax It [&hellip;]<\/p>\n","protected":false},"author":7,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1],"tags":[],"class_list":["post-2003","post","type-post","status-publish","format-standard","hentry","category-python"],"blocksy_meta":[],"_links":{"self":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts\/2003","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/users\/7"}],"replies":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/comments?post=2003"}],"version-history":[{"count":0,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts\/2003\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/media?parent=2003"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/categories?post=2003"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/tags?post=2003"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}