Python 中帶括號和不帶括號呼叫函式
術語“呼叫函式”指的是遞迴,這意味著函式呼叫自身。帶括號的函式定義了一些引數,用於處理特定條件和操作,而不帶括號的函式指的是函式引用。在 Python 中,我們有兩種方法,即函式引用和帶引數的函式,它們將用於解決帶括號和不帶括號的函式呼叫問題。
語法
以下語法在示例中使用
def function_name(): -------- -------- function_name()
這是帶括號函式的表示。
def function_name():
--------
--------
reference = function_name
print("The function reference:", reference)
這是藉助引用表示不帶括號的函式。
帶括號的簡單函式呼叫
以下示例中的程式使用遞迴函式,並應用 print 語句來顯示一些文字。然後使用呼叫函式返回結果。
示例
# invoke the function without parenthesis
def education():
print("Welcome To Tutorialspoint")
education()
輸出
Welcome To Tutorialspoint
帶引數的函式呼叫
在下面的示例中,程式使用一個名為 addition() 的遞迴函式,該函式接受兩個引數 x 和 y,用於對兩個變數進行加法運算。接下來,使用呼叫函式傳遞關於 x 和 y 的兩個值,並將它們儲存在變數 res 中。最後,它將藉助變數 res 列印結果。
示例
def addition(x, y):
return x + y
res = addition(30, 40)
print("The sum of two numbers: ", res)
輸出
The sum of two numbers: 70
分配不帶括號的函式引用
在下面的示例中,程式使用一個名為 Emp() 的函式定義,並應用 print 來顯示一些文字。接下來,它將使用函式引用,其中函式 Emp 將其儲存在變數 result 中。現在使用呼叫函式返回輸出。
示例
def Emp():
print("Python Codeground")
# function reference without parenthesis
result = Emp
result()
輸出
Python Codeground
不帶括號的函式返回值
在下面的示例中,程式使用了三個函式,即 add_string()、merge_stng() 和 without_parenthesis()。第二個函式 merge_stng 接受兩個引數,用於新增兩個字串。接下來,merge_stng 不帶括號地返回結果。merge_stng 的記錄將儲存在名為 add_string 的函式中。接下來使用另一個函式,即 without_parenthesis(),它使用函式 add_string() 設定 merge_stng 函式的引用,並將其儲存在變數 res 中。現在它將列印引用及其執行。最後,我們呼叫名為 without_parenthesis() 的函式以獲取結果。
示例
def add_string():
def merge_stng(str1, str2):
return str1 + str2
# return the function without parenthesis
return merge_stng
def without_parenthesis():
# return the reference of merge_string function
res = add_string()
# prints the reference
print(res)
# executes the reference
print(res('Welcome', ' to India'))
without_parenthesis()
輸出
<function add_string.<locals>.merge_stng at 0x7f176a50b910> Welcome to India
結論
我們討論了四種不同的方法來處理 Python 中帶括號和不帶括號的函式呼叫。沒有使用任何內建函式來執行這些任務。函式呼叫是一種很棒的技術,可以縮短程式碼長度並利用迭代。
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP