Python 使用括号和不使用括号调用函数
调用函数一词是指递归,意味着函数会调用自身。有括号的函数定义了一些参数来处理特定条件和操作,而没有括号的函数是指函数引用。在Python中,我们有两种类型的方法,即函数引用和带参数的函数,用于解决使用括号和不使用括号的调用函数。
语法
以下是示例中使用的语法
def function_name():
--------
--------
function_name()
这是带括号的函数表示。
def function_name():
--------
--------
reference = function_name
print("The function reference:", reference)
这是在没有引用括号的情况下表示函数的方法。
用括号调用简单函数
该程序在以下示例中使用递归函数,并应用打印语句来显示一些文本。然后使用调用函数返回结果。
示例
# 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中使用和不使用括号调用函数。在执行这些任务时没有使用任何内置函数。调用函数是一种令人惊奇的技巧,可以减少代码的长度并利用迭代的优势。