当前位置: 首页>>代码示例>>用法及示例精选>>正文


Python __call__用法及代码示例

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




注:本文由纯净天空筛选整理自rakshitarora大神的英文原创作品 __call__ in Python。非经特殊声明,原始代码版权归原作者所有,本译文的传播和使用请遵循“署名-相同方式共享 4.0 国际 (CC BY-SA 4.0)”协议。