天天看点

__call__方法的运行机制

__call__方法是python的内置方法之一,在类中使用这个内置方法就可以让该类的实例化对象以一个函数的形式运行。

NB(注意): # 后面的部分表示输出结果

代码如下:

class Example:
    def __init__(self):
        print("Instance Created")
    
    # definf __call__ method
    def __call__(self):
        print("Instance is called via special method")
        

# Instance created
main = Example()   # Instance Created

# __call__ method will be called
main() # Instance is called via special method      
class Add: 
    def __init__(self): 
        print("Instance Created") 
  
    # Defining __call__ method 
    def __call__(self, a, b): 
        print(a + b) 
  
# Instance created 
main = Add() 
  
# __call__ method will be called 
main(10, 20)    #  30