Home > Backend Development > Python Tutorial > Introduction to the use of __call__ method in python (with examples)

Introduction to the use of __call__ method in python (with examples)

不言
Release: 2018-09-17 16:38:02
Original
4490 people have browsed it

This article brings you an introduction to the use of the __call__ method in python (with examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

If a class in Python defines the __call__ method, then its instance of this class can be called as a function, that is, it implements the () operator and can call the object protocol

The following is a simple example:

class TmpTest:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __call__(self, x, y):
        self.x, self.y = x, y


a = TmpTest(1, 2)
a(4, 5)
print(a.x, a.y)
Copy after login

In this article, we will not discuss the decoration part. We will use the decorator to explain the use of a __call__ method. If you need to use a class as a decorator, you need to provide this Class implements __call__ method, an example of using __call__ to implement class decorator:

class TmpTest:
    def __init__(self, func):
        self.func=func
    def __call__(self, *args,**kwargs):
        result=self.func(*args,**kwargs)
        return result
@TmpTest
def add_num(x,y):
    return x+y

print(add_num(1,0))
Copy after login

The above is the detailed content of Introduction to the use of __call__ method in python (with examples). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template