-4

Can you please explain the use of the __setattr__ method in the below 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
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Sushil
  • 1
  • What precisely don't you understand? Have you tried employing e.g. `print` to investigate the confusing behaviour? Read the Python documentation regarding that *"magic"* method? – jonrsharpe Oct 09 '16 at 19:27
  • check this http://stackoverflow.com/questions/5755023/why-to-use-setattr-in-python – Alex L Oct 09 '16 at 19:29
  • It makes this class unusable. For value checking use properties. – Daniel Oct 09 '16 at 19:32

1 Answers1

0

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
Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126