當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。