Explain the use of __setattr__
<p>Can you please explain the use of the <code>__setattr__</code> method in the below code :</p>

<pre><code>class Human(object):
    def __setattr__(self,name,value):
        if name == 'gender':
            if value in ('male', 'female'):
                self.gender = value
            else :
                raise AttributeError('Gender can only be Male or Female')

 h = Human()
h.name = 'Mary'
h.gender = 'female'
print h.gender
</code></pre>

<p>In your code, <code>__setattr__()</code> function is making a validation that while assigning the value of <code>self.gender</code>, it's value should be only between <code>male</code> and <code>female</code>. In case of any other value, it will raise <code>AttributeError</code> exception.</p>

<p><em>Note:</em> In your <code>__setattr__()</code> function, there is no call to <code>super</code> of <code>__setattr__</code>, and hence this function is not actually updating the properties of class. You should add below line in your <code>__setattr__()</code> in order to make it work:</p>

<pre><code>super(Human, self).__setattr__(name, value)
</code></pre>

<hr>

<p><strong>Overview about <a href="https://docs.python.org/2/reference/datamodel.html#object.__setattr__" rel="nofollow"><code>.__setattr__(self, name, value)</code></a></strong>:</p>

<p>Whenever you assign any value to the property of the class, <code>__setattr__(self, name, value)</code> function is called where <code>name</code> is the property of <code>class</code> and <code>value</code> is the new value to be assigned. Below is the sample code to demonstrate that:</p>

<pre><code>&gt;&gt;&gt; class MyClass(object):
...     def __init__(self, x, y):
...         self.x = x
...         self.y = y
...     def __setattr__(self, name, value):
...         print 'In Set Attr for: ', name, ', ', value
...         super(MyClass, self).__setattr__(name, value)
...
...
&gt;&gt;&gt; my_object = MyClass(1, 2)
In Set Attr for:  x, 1
In Set Attr for:  y, 2
&gt;&gt;&gt; my_object.x = 10  # &lt;-- Called while assigning value x
In Set Attr for:  x, 10
</code></pre>

python