问题描述
我知道在调用类的实例时会触发类中的 __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__ 特殊方法实战例子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!