📜  __call__ 在Python中

📅  最后修改于: 2022-05-13 01:54:44.410000             🧑  作者: Mango

__call__ 在Python中

Python有一组内置方法, __call__就是其中之一。 __call__方法使Python程序员可以编写实例行为类似于函数并且可以像函数一样调用的类。当实例作为函数时;如果定义了此方法,则x(arg1, arg2, ...)x.__call__(arg1, arg2, ...)的简写。

object() is shorthand for object.__call__()

示例 1:

class Example:
    def __init__(self):
        print("Instance Created")
      
    # Defining __call__ method
    def __call__(self):
        print("Instance is called via special method")
  
# Instance created
e = Example()
  
# __call__ method will be called
e()

输出 :

Instance Created
Instance is called via special method

示例 2:

class Product:
    def __init__(self):
        print("Instance Created")
  
    # Defining __call__ method
    def __call__(self, a, b):
        print(a * b)
  
# Instance created
ans = Product()
  
# __call__ method will be called
ans(10, 20)

输出 :

Instance Created
200