[Tutor] self.name is calling the __set__ method of another class

Arup Rakshit ar at zeit.io
Mon Apr 29 13:55:51 EDT 2019


Hi,

In the following code, class attributes name and email is set to the instances of NonBlank.

class NonBlank:
    def __init__(self, storage_name):
        self.storage_name = storage_name
    
    def __set__(self, instance, value):
        if not isinstance(value, str):
            raise TypeError("%r must be of type 'str'" % self.storage_name)
        elif len(value) == 0:
            raise ValueError("%r must not be empty" % self.storage_name)
        instance.__dict__[self.storage_name] = value

class Customer:
    name = NonBlank('name')
    email = NonBlank('email')
    
    def __init__(self, name, email, fidelity=0):
        self.name = name
        self.email = email
        self.fidelity = fidelity
    
    def full_email(self):
        return '{0} <{1}>'.format(self.name, self.email)
    
if __name__ == '__main__':
    cus = Customer('Arup', 99)

Running this code throws an error:

Traceback (most recent call last):
  File "/Users/aruprakshit/python_playground/pycon2017/decorators_and_descriptors_decoded/customer.py", line 25, in <module>
    cus = Customer('Arup', 99)
  File "/Users/aruprakshit/python_playground/pycon2017/decorators_and_descriptors_decoded/customer.py", line 18, in __init__
    self.email = email
  File "/Users/aruprakshit/python_playground/pycon2017/decorators_and_descriptors_decoded/customer.py", line 7, in __set__
    raise TypeError("%r must be of type 'str'" % self.storage_name)
TypeError: 'email' must be of type 'str'
Process terminated with an exit code of 1

Now I am not getting how the __set__() method from NonBlank is being called inside the __init__() method. Looks like some magic is going on under the hood. Can anyone please explain this how self.name and self.email assignment is called the __set__ from NonBlank? What is the name of this concept?


Thanks,

Arup Rakshit
ar at zeit.io





More information about the Tutor mailing list