Python __call__ special method practical example -


i know __call__ method in class triggered when instance of class called. however, have no idea when can use special method, because 1 can create new method , perform same operation done in __call__ method , instead of calling instance, can call method.

i appreciate if gives me practical usage of special method.

django forms module uses __call__ method nicely implement consistent api form validation. can write own validator form in django function.

def custom_validator(value):     #your validation logic 

django has default built-in validators such email validators, url validators etc., broadly fall under umbrella of regex validators. implement these cleanly, django resorts callable classes (instead of functions). implements default regex validation logic in regexvalidator , extends these classes other validations.

class regexvalidator(object):     def __call__(self, value):         # validation logic  class urlvalidator(regexvalidator):     def __call__(self, value):         super(urlvalidator, self).__call__(value)         #additional logic  class emailvalidator(regexvalidator):     # logic 

now both custom function , built-in emailvalidator can called same syntax.

for v in [custom_validator, emailvalidator()]:     v(value) # <----- 

as can see, implementation in django similar others have explained in answers below. can implemented in other way? could, imho not readable or extensible big framework django.


Comments

Popular posts from this blog

objective c - Change font of selected text in UITextView -

php - Accessing POST data in Facebook cavas app -

c# - Getting control value when switching a view as part of a multiview -