In your code, __setattr__()
function is making a validation that while assigning the value of self.gender
, it's value should be only between male
and female
. In case of any other value, it will raise AttributeError
exception.
Note: In your __setattr__()
function, there is no call to super
of __setattr__
, and hence this function is not actually updating the properties of class. You should add below line in your __setattr__()
in order to make it work:
super(Human, self).__setattr__(name, value)
Overview about .__setattr__(self, name, value)
:
Whenever you assign any value to the property of the class, __setattr__(self, name, value)
function is called where name
is the property of class
and value
is the new value to be assigned. Below is the sample code to demonstrate that:
>>> 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)
...
...
>>> my_object = MyClass(1, 2)
In Set Attr for: x, 1
In Set Attr for: y, 2
>>> my_object.x = 10 # <-- Called while assigning value x
In Set Attr for: x, 10