{"id":4719,"date":"2022-09-12T04:14:22","date_gmt":"2022-09-12T04:14:22","guid":{"rendered":"https:\/\/www.pythontutorial.net\/?page_id=4719"},"modified":"2022-10-01T02:15:23","modified_gmt":"2022-10-01T02:15:23","slug":"python-getattr","status":"publish","type":"page","link":"https:\/\/www.pythontutorial.net\/python-built-in-functions\/python-getattr\/","title":{"rendered":"Python getattr"},"content":{"rendered":"\n<p><strong>Summary<\/strong>: in this tutorial, you&#8217;ll learn how to use the Python <code>getattr()<\/code> function to get a named attribute of an object.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id='introduction-to-python-getattr-function'>Introduction to Python getattr() function <a href=\"#introduction-to-python-getattr-function\" class=\"anchor\" id=\"introduction-to-python-getattr-function\" title=\"Anchor for Introduction to Python getattr() function\">#<\/a><\/h2>\n\n\n\n<p>The <code>getattr()<\/code> function allows you to get the value of the named attribute of an object. Here&#8217;s the syntax of the <code>getattr()<\/code> function:<\/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\">getattr(object, name&#91;, default])<\/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>getattr()<\/code> function accepts three parameters:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><code>object<\/code> is the object from which you want to get the value of a named attribute.<\/li><li><code>name<\/code> is a string that specifies the attribute name of the object.<\/li><li><code>default<\/code>: if the named attribute doesn&#8217;t exist in the object, the <code>getattr()<\/code> function returns the default. If you omit the default and the named attribute doesn&#8217;t exist, the function will raise an <code>AttributeError<\/code> exception.<\/li><\/ul>\n\n\n\n<h2 class=\"wp-block-heading\" id='python-getattr-function-example'>Python getattr() function example <a href=\"#python-getattr-function-example\" class=\"anchor\" id=\"python-getattr-function-example\" title=\"Anchor for Python getattr() function example\">#<\/a><\/h2>\n\n\n\n<p>The following example illustrates how to use the <code>getattr()<\/code> to get the attribute values of an object:<\/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\">Member<\/span>:<\/span>\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">__init__<\/span><span class=\"hljs-params\">(self, name, email)<\/span>:<\/span>\n        self.name = name\n        self.email = email\n\n\nmember = Member(<span class=\"hljs-string\">'John Doe'<\/span>, <span class=\"hljs-string\">'john@pythontutorial.net'<\/span>)\nname = getattr(member, <span class=\"hljs-string\">'name'<\/span>)\nprint(name)  <span class=\"hljs-comment\"># ? John Doe<\/span>\n\nemail = getattr(member, <span class=\"hljs-string\">'email'<\/span>)\nprint(name)  <span class=\"hljs-comment\"># ? john@pythontutorial.net<\/span>\n\nage = getattr(member, <span class=\"hljs-string\">'age'<\/span>)\nprint(age)  <span class=\"hljs-comment\"># ? AttributeError<\/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>How it works.<\/p>\n\n\n\n<p>First, define a class <code>Member<\/code> with two attributes, <code>name<\/code> and <code>age<\/code>:<\/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\">Member<\/span>:<\/span>\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">__init__<\/span><span class=\"hljs-params\">(self, name, email)<\/span>:<\/span>\n        self.name = name\n        self.email = email<\/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, create a new instance of the <code>Member<\/code> class:<\/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\">member = Member(<span class=\"hljs-string\">'John Doe'<\/span>, <span class=\"hljs-string\">'john@pythontutorial.net'<\/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>Third, use the <code>getattr()<\/code> function to get the values of the <code>name<\/code> and <code>email<\/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\">name = getattr(member, <span class=\"hljs-string\">'name'<\/span>)\nprint(name)  <span class=\"hljs-comment\"># ? John Doe<\/span>\n\nemail = getattr(member, <span class=\"hljs-string\">'email'<\/span>)\nprint(name)  <span class=\"hljs-comment\"># ? john@pythontutorial.net<\/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>It is the same as accessing the attributes directly:<\/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\">print(member.name)  <span class=\"hljs-comment\"># ? John Doe<\/span>\nprint(member.email)  <span class=\"hljs-comment\"># ? john@pythontutorial.net<\/span><\/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>Finally, attempt to access the non-existing attribute <code>age<\/code>. It&#8217;ll raise an <code>AttributeError<\/code> exception.<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-7\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\">age = getattr(member, <span class=\"hljs-string\">'age'<\/span>)\nprint(age)  <span class=\"hljs-comment\"># ? AttributeError<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-7\"><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>To avoid the exception, you can pass <code>None<\/code> as the default value like this:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-8\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\">age = getattr(member, <span class=\"hljs-string\">'age'<\/span>, <span class=\"hljs-literal\">None<\/span>)<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-8\"><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, the <code>age<\/code> is <code>None<\/code>.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id='a-practical-example-of-the-python-getattr-function'>A practical example of the Python getattr() function <a href=\"#a-practical-example-of-the-python-getattr-function\" class=\"anchor\" id=\"a-practical-example-of-the-python-getattr-function\" title=\"Anchor for A practical example of the Python getattr() function\">#<\/a><\/h2>\n\n\n\n<p>In practice, you&#8217;ll use the <code>getattr()<\/code> function to call the method of an object dynamically. Note that a <a href=\"https:\/\/www.pythontutorial.net\/python-oop\/python-methods\/\">method<\/a> is also an attribute of an object.<\/p>\n\n\n\n<p>Suppose, you need to validate the name and email with the following rules:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><code>name<\/code> is required i.e., its length is greater than zero.<\/li><li><code>email<\/code> is a valid email address<\/li><\/ul>\n\n\n\n<p>To do that, you can create a reusable Validation class and use it as follows:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-9\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\">validation = Validation()\ndata = {<span class=\"hljs-string\">'name'<\/span>: <span class=\"hljs-string\">''<\/span>, <span class=\"hljs-string\">'email'<\/span>: <span class=\"hljs-string\">'test'<\/span>}\nrules = {<span class=\"hljs-string\">'name'<\/span>: <span class=\"hljs-string\">'required'<\/span>, <span class=\"hljs-string\">'email'<\/span>: <span class=\"hljs-string\">'email'<\/span>}\nerrors = validation.validate(data, rules)\nprint(errors)<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-9\"><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 code, the <code>data<\/code> and <code>rules<\/code> are dictionaries.<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>Each item in the data dictionary has a field name and value. <\/li><li>Each item in the rules dictionary has the field name and rule, which can be either <code>required<\/code> or <code>email<\/code>.<\/li><\/ul>\n\n\n\n<p>The code should return the following output:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-10\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\">{\n <span class=\"hljs-string\">'name'<\/span>: <span class=\"hljs-string\">'The name is required'<\/span>, \n <span class=\"hljs-string\">'email'<\/span>: <span class=\"hljs-string\">'The email is not a valid email address'<\/span>\n}<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-10\"><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>Let&#8217;s develop the <code>Validation<\/code> class.<\/p>\n\n\n\n<p>First, define a <code>Validation<\/code> class:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-11\" 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\">Validation<\/span>:<\/span>\n    <span class=\"hljs-keyword\">pass<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-11\"><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, declare the error messages (<code>ERRORS<\/code>) for the <code>required<\/code> and <code>email<\/code> rules:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-12\" 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\">Validation<\/span>:<\/span>\n    ERRORS = {\n        <span class=\"hljs-string\">'required'<\/span>: <span class=\"hljs-string\">'The {} is required'<\/span>,\n        <span class=\"hljs-string\">'email'<\/span>: <span class=\"hljs-string\">'The {} is not a valid email address'<\/span>\n    }<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-12\"><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>Third, define the <code>required()<\/code> method that returns <code>True<\/code> if the length of a value is greater than zero and <code>email()<\/code>  method that returns <code>True<\/code> if a value is a valid email address:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-13\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-keyword\">import<\/span> re\n\n<span class=\"hljs-class\"><span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">Validation<\/span>:<\/span>\n    ERRORS = {\n        <span class=\"hljs-string\">'required'<\/span>: <span class=\"hljs-string\">'The {} is required'<\/span>,\n        <span class=\"hljs-string\">'email'<\/span>: <span class=\"hljs-string\">'The {} is not a valid email address'<\/span>\n    }\n\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>\n        <span class=\"hljs-keyword\">return<\/span> len(value) &gt; <span class=\"hljs-number\">0<\/span>\n\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>\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>\n        <span class=\"hljs-keyword\">return<\/span> re.fullmatch(pattern, value)<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-13\"><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>To validate an email address, the <code>email()<\/code> method uses the <code>fullmatch()<\/code> function from the <a href=\"https:\/\/www.pythontutorial.net\/python-regex\/python-regular-expressions\/\">regular expression<\/a> (re) module.<\/p>\n\n\n\n<p>Finally, define the <code>validate()<\/code> method:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-14\" 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\">Validation<\/span>:<\/span>\n    ERRORS = {\n        <span class=\"hljs-string\">'required'<\/span>: <span class=\"hljs-string\">'The {} is required'<\/span>,\n        <span class=\"hljs-string\">'email'<\/span>: <span class=\"hljs-string\">'The {} is not a valid email address'<\/span>\n    }\n\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>\n        <span class=\"hljs-keyword\">return<\/span> len(value) &gt; <span class=\"hljs-number\">0<\/span>\n\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>\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>\n        <span class=\"hljs-keyword\">return<\/span> re.fullmatch(pattern, value)\n\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>\n        errors = {}\n        <span class=\"hljs-keyword\">for<\/span> field, rule <span class=\"hljs-keyword\">in<\/span> rules.items():\n            is_valid_method = getattr(self, rule)\n            <span class=\"hljs-keyword\">if<\/span> <span class=\"hljs-keyword\">not<\/span> is_valid_method(data&#91;field]):\n                errors&#91;field] = self.ERRORS&#91;rule].format(field)\n\n        <span class=\"hljs-keyword\">return<\/span> errors<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-14\"><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 the <code>validate()<\/code> method:<\/p>\n\n\n\n<ol class=\"wp-block-list\"><li>Initialize an errors dictionary to store error messages.<\/li><li>Iterate the rules from the rules dictionary.<\/li><li>For each rule, use the <code>getattr()<\/code> function to find the method that is corresponding to the rule. For example, the <code>getattr()<\/code> returns the <code>required<\/code> method for the <code>required<\/code> rule and <code>email<\/code> method for the <code>email<\/code> rule.<\/li><li>Call the method dynamically to validate data. If the method returns <code>False<\/code>, add the error message to the <code>errors<\/code> dictionary.<\/li><li>Return the <code>errors<\/code>.<\/li><\/ol>\n\n\n\n<p>Put it all together.<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-15\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\">\n<span class=\"hljs-keyword\">import<\/span> re\n\n\n<span class=\"hljs-class\"><span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">Validation<\/span>:<\/span>\n    ERRORS = {\n        <span class=\"hljs-string\">'required'<\/span>: <span class=\"hljs-string\">'The {} is required'<\/span>,\n        <span class=\"hljs-string\">'email'<\/span>: <span class=\"hljs-string\">'The {} is not a valid email address'<\/span>\n    }\n\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>\n        <span class=\"hljs-keyword\">return<\/span> len(value) &gt; <span class=\"hljs-number\">0<\/span>\n\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>\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>\n        <span class=\"hljs-keyword\">return<\/span> re.fullmatch(pattern, value)\n\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>\n        errors = {}\n        <span class=\"hljs-keyword\">for<\/span> field, rule <span class=\"hljs-keyword\">in<\/span> rules.items():\n            is_valid_method = getattr(self, rule)\n            <span class=\"hljs-keyword\">if<\/span> <span class=\"hljs-keyword\">not<\/span> is_valid_method(data&#91;field]):\n                errors&#91;field] = self.ERRORS&#91;rule].format(field)\n\n        <span class=\"hljs-keyword\">return<\/span> errors\n\n\nvalidation = Validation()\ndata = {<span class=\"hljs-string\">'name'<\/span>: <span class=\"hljs-string\">''<\/span>, <span class=\"hljs-string\">'email'<\/span>: <span class=\"hljs-string\">'test'<\/span>}\nrules = {<span class=\"hljs-string\">'name'<\/span>: <span class=\"hljs-string\">'required'<\/span>, <span class=\"hljs-string\">'email'<\/span>: <span class=\"hljs-string\">'email'<\/span>}\nerrors = validation.validate(data, rules)\nprint(errors)<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-15\"><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>Output:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-16\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\">\n<span class=\"hljs-keyword\">import<\/span> re\n\n\n<span class=\"hljs-class\"><span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">Validation<\/span>:<\/span>\n    ERRORS = {\n        <span class=\"hljs-string\">'required'<\/span>: <span class=\"hljs-string\">'The {} is required'<\/span>,\n        <span class=\"hljs-string\">'email'<\/span>: <span class=\"hljs-string\">'The {} is not a valid email address'<\/span>\n    }\n\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>\n        <span class=\"hljs-keyword\">return<\/span> len(value) &gt; <span class=\"hljs-number\">0<\/span>\n\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>\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>\n        <span class=\"hljs-keyword\">return<\/span> re.fullmatch(pattern, value)\n\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>\n        errors = {}\n        <span class=\"hljs-keyword\">for<\/span> field, rule <span class=\"hljs-keyword\">in<\/span> rules.items():\n            is_valid_method = getattr(self, rule)\n            <span class=\"hljs-keyword\">if<\/span> <span class=\"hljs-keyword\">not<\/span> is_valid_method(data&#91;field]):\n                errors&#91;field] = self.ERRORS&#91;rule].format(field)\n\n        <span class=\"hljs-keyword\">return<\/span> errors\n\n\n<span class=\"hljs-keyword\">if<\/span> __name__ == <span class=\"hljs-string\">'__main__'<\/span>:\n    validation = Validation()\n    data = {<span class=\"hljs-string\">'name'<\/span>: <span class=\"hljs-string\">''<\/span>, <span class=\"hljs-string\">'email'<\/span>: <span class=\"hljs-string\">'test'<\/span>}\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>}\n    errors = validation.validate(data, rules)\n    print(errors)<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-16\"><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>Output:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-17\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\">{\n <span class=\"hljs-string\">'name'<\/span>: <span class=\"hljs-string\">'The name is required'<\/span>, \n <span class=\"hljs-string\">'email'<\/span>: <span class=\"hljs-string\">'The email is not a valid email address'<\/span>\n}<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-17\"><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>If you pass the valid data, the errors will be empty:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-18\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-comment\"># Validation class<\/span>\n<span class=\"hljs-keyword\">if<\/span> __name__ == <span class=\"hljs-string\">'__main__'<\/span>:\n    validation = Validation()\n    data = {<span class=\"hljs-string\">'name'<\/span>: <span class=\"hljs-string\">'John'<\/span>, <span class=\"hljs-string\">'email'<\/span>: <span class=\"hljs-string\">'john@pythontutorial.net'<\/span>}\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>}\n    errors = validation.validate(data, rules)\n    print(errors)<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-18\"><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 this code should contain the <code>Validation<\/code> class to execute successfully<\/p>\n\n\n\n<p>Output:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-19\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\">{}<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-19\"><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>Note that you can hide the <code>required()<\/code> and <code>email()<\/code> method by making them <a href=\"https:\/\/www.pythontutorial.net\/python-oop\/python-private-attributes\/\">private<\/a>. In this case, you also need to pass the rule prefixed with an underscore (<code>_<\/code>) to the <code>getattr()<\/code> function get the corresponding method:<\/p>\n\n\n<pre class=\"wp-block-code\"><span><code class=\"hljs\">\nimport re\n\nclass Validation:\n    ERRORS = {\n        'required': 'The {} is required',\n        'email': 'The {} is not a valid email address'\n    }\n\n    def _required(self, value):\n        return len(value) &gt; 0\n\n    def _email(self, value):\n        pattern = r'\\b&#91;A-Za-z0-9._%+-]+@&#91;A-Za-z0-9.-]+\\.&#91;A-Z|a-z]{2,}\\b'\n        return re.fullmatch(pattern, value)\n\n    def validate(self, data, rules):\n        errors = {}\n        for field, rule in rules.items():\n            is_valid_method = getattr(self, f'_{rule}')\n            if not is_valid_method(data&#91;field]):\n                errors&#91;field] = self.ERRORS&#91;rule].format(field)\n\n        return errors<\/code><\/span><\/pre>\n\n\n<p>Notice the following line of code:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-20\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">is_valid_method = getattr(<span class=\"hljs-keyword\">self<\/span>, f<span class=\"hljs-string\">'_{rule}'<\/span>)<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-20\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\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>getattr()<\/code> function to get a value of a named attribute of an object.<\/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=\"4719\"\n\t\t\t\tdata-post-url=\"https:\/\/www.pythontutorial.net\/python-built-in-functions\/python-getattr\/\"\n\t\t\t\tdata-post-title=\"Python getattr\"\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=\"4719\"\n\t\t\t\tdata-post-url=\"https:\/\/www.pythontutorial.net\/python-built-in-functions\/python-getattr\/\"\n\t\t\t\tdata-post-title=\"Python getattr\"\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 getattr() function to get a named attribute of an object.<\/p>\n","protected":false},"author":1,"featured_media":0,"parent":1055,"menu_order":10,"comment_status":"closed","ping_status":"closed","template":"","meta":{"footnotes":""},"class_list":["post-4719","page","type-page","status-publish","hentry"],"_links":{"self":[{"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/pages\/4719","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=4719"}],"version-history":[{"count":0,"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/pages\/4719\/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=4719"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}