Python __call__ special method practical example

后端 未结 14 1629
感动是毒
感动是毒 2020-11-28 00:28

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

14条回答
  •  抹茶落季
    2020-11-28 01:13

    One common example is the __call__ in functools.partial, here is a simplified version (with Python >= 3.5):

    class partial:
        """New function with partial application of the given arguments and keywords."""
    
        def __new__(cls, func, *args, **kwargs):
            if not callable(func):
                raise TypeError("the first argument must be callable")
            self = super().__new__(cls)
    
            self.func = func
            self.args = args
            self.kwargs = kwargs
            return self
    
        def __call__(self, *args, **kwargs):
            return self.func(*self.args, *args, **self.kwargs, **kwargs)
    

    Usage:

    def add(x, y):
        return x + y
    
    inc = partial(add, y=1)
    print(inc(41))  # 42
    

提交回复
热议问题