{"id":4724,"date":"2022-09-12T05:00:29","date_gmt":"2022-09-12T05:00:29","guid":{"rendered":"https:\/\/www.pythontutorial.net\/?page_id=4724"},"modified":"2022-09-12T06:27:56","modified_gmt":"2022-09-12T06:27:56","slug":"python-hasattr","status":"publish","type":"page","link":"https:\/\/www.pythontutorial.net\/python-built-in-functions\/python-hasattr\/","title":{"rendered":"Python hasattr"},"content":{"rendered":"\n<p><strong>Summary<\/strong>: in this tutorial, you&#8217;ll learn how to use the Python <code>hasattr()<\/code> function to check if an object has a named attribute.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id='introduction-to-python-hasattr-function'>Introduction to Python hasattr() function <a href=\"#introduction-to-python-hasattr-function\" class=\"anchor\" id=\"introduction-to-python-hasattr-function\" title=\"Anchor for Introduction to Python hasattr() function\">#<\/a><\/h2>\n\n\n\n<p>The <code>hasattr()<\/code> function returns <code>True<\/code> if an object has a named attribute specified by a string:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-1\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\">hasattr(object, name)<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-1\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>The <code>hasattr()<\/code> function has two parameters:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><code>object<\/code> is the object that you want to check.<\/li><li><code>name<\/code> is a string that specifies the name of the attribute.<\/li><\/ul>\n\n\n\n<p>The <code>hasattr()<\/code> returns <code>True<\/code> if the object has an attribute with the name specified by the string <code>name<\/code> or <code>False<\/code> otherwise.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id='python-hasattr-function-example'>Python hasattr() function example <a href=\"#python-hasattr-function-example\" class=\"anchor\" id=\"python-hasattr-function-example\" title=\"Anchor for Python hasattr() function example\">#<\/a><\/h2>\n\n\n\n<p>The following example illustrates how to use the <code>hasattr()<\/code> function:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-2\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-class\"><span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">Message<\/span>:<\/span>\n    error = <span class=\"hljs-string\">'error'<\/span>\n    warning = <span class=\"hljs-string\">'warning'<\/span>\n    info = <span class=\"hljs-string\">'info'<\/span>\n    success = <span class=\"hljs-string\">'success'<\/span>\n\n\nresult = hasattr(Message, <span class=\"hljs-string\">'error'<\/span>)\nprint(result)  <span class=\"hljs-comment\"># ? True<\/span>\n\n\nresult = hasattr(Message, <span class=\"hljs-string\">'information'<\/span>)\nprint(result)  <span class=\"hljs-comment\"># ? False<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-2\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"note\">Note that everything in Python is an object including a <a href=\"https:\/\/www.pythontutorial.net\/python-oop\/python-class\/\">class<\/a>. Therefore, you can pass a class to the <code>hasattr()<\/code> function.<\/p>\n\n\n\n<p>How it works.<\/p>\n\n\n\n<p>First, define the <code>Message<\/code> class with four class attributes:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-3\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-class\"><span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">Message<\/span>:<\/span>\n    error = <span class=\"hljs-string\">'error'<\/span>\n    warning = <span class=\"hljs-string\">'warning'<\/span>\n    info = <span class=\"hljs-string\">'info'<\/span>\n    success = <span class=\"hljs-string\">'success'<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-3\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Second, use the <code>hasattr()<\/code> to check if the <code>Message<\/code> class has the <code>error<\/code> attribute:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-4\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\">result = hasattr(Message, <span class=\"hljs-string\">'error'<\/span>)\nprint(result)  <span class=\"hljs-comment\"># ? True<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-4\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>In this case, it returns <code>True<\/code> because the <code>Message<\/code> class has the <code>error<\/code> attribute.<\/p>\n\n\n\n<p>Third, use the <code>hasattr()<\/code> to check if the <code>Message<\/code> has the <code>information<\/code> attribute:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-5\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\">result = hasattr(Message, <span class=\"hljs-string\">'information'<\/span>)\nprint(result)  <span class=\"hljs-comment\"># ? False<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-5\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>In this example, the <code>hasattr()<\/code> returns <code>False<\/code> because the <code>Message<\/code> class doesn&#8217;t have the <code>information<\/code> attribute.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id='a-practical-example-of-python-hasattr-function'>A practical example of Python hasattr() function <a href=\"#a-practical-example-of-python-hasattr-function\" class=\"anchor\" id=\"a-practical-example-of-python-hasattr-function\" title=\"Anchor for A practical example of Python hasattr() function\">#<\/a><\/h2>\n\n\n\n<p>In practice, you use the <code><code>hasattr()<\/code><\/code> function to check if an object has an attribute or a method with the name is only known at runtime before accessing it. For example, you can use the <code><code>hasattr()<\/code><\/code> to check if an object has a method before calling it. <\/p>\n\n\n\n<p>The following example enhances the Validation class from the <a href=\"https:\/\/www.pythontutorial.net\/python-built-in-functions\/python-getattr\/\"><code>getattr()<\/code> tutorial<\/a>:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-6\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\">\r<span class=\"hljs-keyword\">import<\/span> re\r\n\r\n\r\n<span class=\"hljs-class\"><span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">Validation<\/span>:<\/span>\r\n    ERRORS = {\r\n        <span class=\"hljs-string\">'required'<\/span>: <span class=\"hljs-string\">'The {} is required'<\/span>,\r\n        <span class=\"hljs-string\">'email'<\/span>: <span class=\"hljs-string\">'The {} is not a valid email address'<\/span>\r\n    }\r\n\r\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">_required<\/span><span class=\"hljs-params\">(self, value)<\/span>:<\/span>\r\n        <span class=\"hljs-keyword\">return<\/span> len(value) &gt; <span class=\"hljs-number\">0<\/span>\r\n\r\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">_email<\/span><span class=\"hljs-params\">(self, value)<\/span>:<\/span>\r\n        pattern = <span class=\"hljs-string\">r'\\b&#91;A-Za-z0-9._%+-]+@&#91;A-Za-z0-9.-]+\\.&#91;A-Z|a-z]{2,}\\b'<\/span>\r\n        <span class=\"hljs-keyword\">return<\/span> re.fullmatch(pattern, value)\r\n\r\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">validate<\/span><span class=\"hljs-params\">(self, data, rules)<\/span>:<\/span>\r\n        errors = {}\r\n        <span class=\"hljs-keyword\">for<\/span> field, rule <span class=\"hljs-keyword\">in<\/span> rules.items():\r\n            <span class=\"hljs-keyword\">if<\/span> hasattr(self, <span class=\"hljs-string\">f'_<span class=\"hljs-subst\">{rule}<\/span>'<\/span>):\r\n                is_valid_method = getattr(self, <span class=\"hljs-string\">f'_<span class=\"hljs-subst\">{rule}<\/span>'<\/span>)\r\n                <span class=\"hljs-keyword\">if<\/span> <span class=\"hljs-keyword\">not<\/span> is_valid_method(data&#91;field]):\r\n                    errors&#91;field] = self.ERRORS&#91;rule].format(field)\r\n            <span class=\"hljs-keyword\">else<\/span>:\r\n                errors&#91;field] = <span class=\"hljs-string\">f'The rule <span class=\"hljs-subst\">{rule}<\/span> is not supported'<\/span>\r\n\r\n        <span class=\"hljs-keyword\">return<\/span> errors\r\n\r\n\r\n<span class=\"hljs-keyword\">if<\/span> __name__ == <span class=\"hljs-string\">'__main__'<\/span>:\r\n    validation = Validation()\r\n    data = {<span class=\"hljs-string\">'name'<\/span>: <span class=\"hljs-string\">'Jane Doe'<\/span>, <span class=\"hljs-string\">'email'<\/span>: <span class=\"hljs-string\">'jane@pythontutorial.net'<\/span>}\r\n    rules = {<span class=\"hljs-string\">'name'<\/span>: <span class=\"hljs-string\">'required'<\/span>, <span class=\"hljs-string\">'email'<\/span>: <span class=\"hljs-string\">'email'<\/span>}\r\n    errors = validation.validate(data, rules)\r\n    print(errors)\n<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-6\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>In this example, the <code>hasattr()<\/code> checks if the <code>Validation<\/code> class has a method with a name that matches a rule before calling it. If the method doesn&#8217;t exist, the <code>validate()<\/code> method adds an entry to the <code>errors<\/code> dictionary.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id='summary'>Summary <a href=\"#summary\" class=\"anchor\" id=\"summary\" title=\"Anchor for Summary\">#<\/a><\/h2>\n\n\n\n<ul class=\"wp-block-list\"><li>Use Python <code>hasattr()<\/code> to check if an object has an attribute with a name.<\/li><\/ul>\n<div class=\"helpful-block-content\" data-title=\"\">\n\t<header>\n\t\t<div class=\"wth-question\">Was this tutorial helpful ?<\/div>\n\t\t<div class=\"wth-thumbs\">\n\t\t\t<button\n\t\t\t\tdata-post=\"4724\"\n\t\t\t\tdata-post-url=\"https:\/\/www.pythontutorial.net\/python-built-in-functions\/python-hasattr\/\"\n\t\t\t\tdata-post-title=\"Python hasattr\"\n\t\t\t\tdata-response=\"1\"\n\t\t\t\tclass=\"wth-btn-rounded wth-yes-btn\"\n\t\t\t>\n\t\t\t\t<svg\n\t\t\t\t\txmlns=\"http:\/\/www.w3.org\/2000\/svg\"\n\t\t\t\t\tviewBox=\"0 0 24 24\"\n\t\t\t\t\tfill=\"none\"\n\t\t\t\t\tstroke=\"currentColor\"\n\t\t\t\t\tstroke-width=\"2\"\n\t\t\t\t\tstroke-linecap=\"round\"\n\t\t\t\t\tstroke-linejoin=\"round\"\n\t\t\t\t\tclass=\"feather feather-thumbs-up block w-full h-full\"\n\t\t\t\t>\n\t\t\t\t\t<path\n\t\t\t\t\t\td=\"M14 9V5a3 3 0 0 0-3-3l-4 9v11h11.28a2 2 0 0 0 2-1.7l1.38-9a2 2 0 0 0-2-2.3zM7 22H4a2 2 0 0 1-2-2v-7a2 2 0 0 1 2-2h3\"\n\t\t\t\t\t><\/path>\n\t\t\t\t<\/svg>\n\t\t\t\t<span class=\"sr-only\"> Yes <\/span>\n\t\t\t<\/button>\n\n\t\t\t<button\n\t\t\t\tdata-response=\"0\"\n\t\t\t\tdata-post=\"4724\"\n\t\t\t\tdata-post-url=\"https:\/\/www.pythontutorial.net\/python-built-in-functions\/python-hasattr\/\"\n\t\t\t\tdata-post-title=\"Python hasattr\"\n\t\t\t\tclass=\"wth-btn-rounded wth-no-btn\"\n\t\t\t>\n\t\t\t\t<svg\n\t\t\t\t\txmlns=\"http:\/\/www.w3.org\/2000\/svg\"\n\t\t\t\t\tviewBox=\"0 0 24 24\"\n\t\t\t\t\tfill=\"none\"\n\t\t\t\t\tstroke=\"currentColor\"\n\t\t\t\t\tstroke-width=\"2\"\n\t\t\t\t\tstroke-linecap=\"round\"\n\t\t\t\t\tstroke-linejoin=\"round\"\n\t\t\t\t>\n\t\t\t\t\t<path\n\t\t\t\t\t\td=\"M10 15v4a3 3 0 0 0 3 3l4-9V2H5.72a2 2 0 0 0-2 1.7l-1.38 9a2 2 0 0 0 2 2.3zm7-13h2.67A2.31 2.31 0 0 1 22 4v7a2.31 2.31 0 0 1-2.33 2H17\"\n\t\t\t\t\t><\/path>\n\t\t\t\t<\/svg>\n\t\t\t\t<span class=\"sr-only\"> No <\/span>\n\t\t\t<\/button>\n\t\t<\/div>\n\t<\/header>\n\n\t<div class=\"wth-form hidden\">\n\t\t<div class=\"wth-form-wrapper\">\n\t\t\t<div class=\"wth-title\"><\/div>\n\t\t\t<textarea class=\"wth-message\"><\/textarea>\n\t\t\t<input type=\"button\" name=\"wth-submit\" class=\"wth-btn wth-btn-submit\" id=\"wth-submit\" \/>\n\t\t\t<input type=\"button\" class=\"wth-btn wth-btn-cancel\" value=\"Cancel\" \/>\n\t\t<\/div>\n\t<\/div>\n<\/div>\n","protected":false},"excerpt":{"rendered":"<p>In this tutorial, you&#8217;ll learn how to use the Python hasattr() function to check if an object has a named attribute.<\/p>\n","protected":false},"author":1,"featured_media":0,"parent":1055,"menu_order":11,"comment_status":"closed","ping_status":"closed","template":"","meta":{"footnotes":""},"class_list":["post-4724","page","type-page","status-publish","hentry"],"_links":{"self":[{"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/pages\/4724","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/pages"}],"about":[{"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/types\/page"}],"author":[{"embeddable":true,"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/comments?post=4724"}],"version-history":[{"count":0,"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/pages\/4724\/revisions"}],"up":[{"embeddable":true,"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/pages\/1055"}],"wp:attachment":[{"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/media?parent=4724"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}