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


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。