Python callable() 函式



**Python callable() 函式** 用於確定作為引數傳遞的物件是否可以被呼叫。如果物件實現了 **__call__()** 方法,則稱該物件是可呼叫的。這裡,傳遞的物件可以是函式、方法、變數和類。

如果指定的物件是可呼叫的,則此函式返回 True,否則返回 False。請記住,雖然 **callable()** 函式可能會返回 TRUE,但並不一定表示物件總是可呼叫的。可能存在它失敗的情況。但是,如果返回值為 FALSE,則可以確定該物件不可呼叫。

**callable()** 函式是 內建函式 之一,不需要匯入任何模組。

語法

Python **callable()** 函式的語法如下所示:

callable(object)

引數

Python **callable()** 函式接受一個引數:

返回值

Python **callable()** 函式返回一個 布林值

callable() 函式示例

練習以下示例以瞭解 Python 中 **callable()** 函式的使用方法

示例:callable() 函式的使用

以下示例演示了 Python callable() 函式的基本用法。這裡我們建立了一個使用者定義的函式,並應用 callable() 函式來檢查給定的函式是否可呼叫。

def checkerFun():
    return "This is Tutorialspoint"

output = callable(checkerFun)
print("Is the given method is callable:", output) 

當我們執行上述程式時,它會產生以下結果:

Is the given method is callable: True

示例:Lambda 表示式和 callable() 函式

在下面的程式碼中,我們有一個 lambda 表示式,callable() 函式檢查此表示式是否可以被呼叫。由於此 lambda 表示式是可呼叫的,因此此方法將返回 True。

lambdaExp = lambda x: x * 3
output = callable(lambdaExp)
print("Is the given lambda expression is callable:", output)

以下是上述程式碼的輸出:

Is the given lambda expression is callable: True

示例:使用 callable() 函式與類和例項

下面的程式碼演示瞭如何使用 callable() 函式與給定的類及其例項。由於類和例項是可呼叫的,因此此方法在這兩種情況下都將返回 True。

class NewClass:
   def __call__(self):
      print("Tutorialspoint")

print("Is the class is callable:")
print(callable(NewClass))  

instanceOfClass = NewClass()
print("Is the instance is callable:")
print(callable(instanceOfClass)) 

上述程式碼的輸出如下所示:

Is the class is callable:
True
Is the instance is callable:
True

示例:使用 callable() 函式與字串物件

在下面的程式碼中,建立了一個字串。然後,藉助 callable() 函式,我們檢查傳遞的字串是否可呼叫。

nonCallableStr = "I am not callable String"
output = callable(nonCallableStr)
print("Is the string is callable:", output)

以下是上述程式碼的輸出:

Is the string is callable: False
python_built_in_functions.htm
廣告