Python __call__特殊方法的实际示例 [英] Python __call__ special method practical example
问题描述
我知道调用类的实例时会触发类中的__call__
方法.但是,我不知道何时可以使用这种特殊方法,因为一个人可以简单地创建一个新方法并执行与__call__
方法相同的操作,而无需调用实例,而可以调用该方法.
I know that __call__
method in a class is triggered when the instance of a class is called. However, I have no idea when I can use this special method, because one can simply create a new method and perform the same operation done in __call__
method and instead of calling the instance, you can call the method.
如果有人给我这种特殊方法的实际用法,我将不胜感激.
I would really appreciate it if someone gives me a practical usage of this special method.
推荐答案
Django表单模块很好地使用__call__
方法来实现用于表单验证的一致API.您可以在Django中将自己的验证器作为函数编写.
Django forms module uses __call__
method nicely to implement a consistent API for form validation. You can write your own validator for a form in Django as a function.
def custom_validator(value):
#your validation logic
Django有一些默认的内置验证器,例如电子邮件验证器,URL验证器等,它们大体上属于RegEx验证器.为了干净地实现这些,Django求助于可调用类(而不是函数).它在RegexValidator中实现默认的Regex验证逻辑,然后扩展这些类以进行其他验证.
Django has some default built-in validators such as email validators, url validators etc., which broadly fall under the umbrella of RegEx validators. To implement these cleanly, Django resorts to callable classes (instead of functions). It implements default Regex Validation logic in a RegexValidator and then extends these classes for 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):
# some logic
现在可以使用相同的语法调用自定义函数和内置的EmailValidator.
Now both your custom function and built-in EmailValidator can be called with the same syntax.
for v in [custom_validator, EmailValidator()]:
v(value) # <-----
如您所见,Django中的此实现类似于其他人在下面的答案中解释的实现.可以通过其他任何方式实现吗?您可以,但是恕我直言,对于像Django这样的大型框架,它的可读性或扩展性都不那么好.
As you can see, this implementation in Django is similar to what others have explained in their answers below. Can this be implemented in any other way? You could, but IMHO it will not be as readable or as easily extensible for a big framework like Django.
这篇关于Python __call__特殊方法的实际示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!