从函数返回一个函数Python
Python中的函数是一流的对象。语言中的一流对象始终被统一处理。它们可以存储在数据结构中,作为参数传递,或者在控制结构中使用。
一等函数的性质:
- 函数是 Object 类型的实例。
- 您可以将函数存储在变量中。
- 您可以将函数作为参数传递给另一个函数。
- 您可以从函数。
- 您可以将它们存储在数据结构中,例如哈希表、列表……
示例 1:没有参数的函数
在此示例中,第一种方法是 A(),第二种方法是 B()。 A() 方法返回 B() 方法,该方法被保存为名称为 returned_function 的对象,并将用于调用第二个方法。
Python3
# define two methods
# second method that will be returned
# by first method
def B():
print("Inside the method B.")
# first method that return second method
def A():
print("Inside the method A.")
# return second method
return B
# form a object of first method
# i.e; second method
returned_function = A()
# call second method by first method
returned_function()
Python3
# define two methods
# second method that will be returned
# by first method
def B(st2):
print("Good " + st2 + ".")
# first method that return second method
def A(st1, st2):
print(st1 + " and ", end = "")
# return second method
return B(st2)
# call first method that do two work:
# 1. execute the body of first method, and
# 2. execute the body of second method as
# first method return the second method
A("Hello", "Morning")
Python3
# first method that return second method
def A(u, v):
w = u + v
z = u - v
# return second method without name
return lambda: print(w * z)
# form a object of first method
# i.e; second method
returned_function = A(5, 2)
# check object
print(returned_function)
# call second method by first method
returned_function()
输出 :
Inside the method A.
Inside the method B.
示例 2:带参数的函数
在此示例中,第一种方法是 A(),第二种方法是 B()。此处调用 A() 方法,该方法返回 B() 方法,即;执行这两个功能。
Python3
# define two methods
# second method that will be returned
# by first method
def B(st2):
print("Good " + st2 + ".")
# first method that return second method
def A(st1, st2):
print(st1 + " and ", end = "")
# return second method
return B(st2)
# call first method that do two work:
# 1. execute the body of first method, and
# 2. execute the body of second method as
# first method return the second method
A("Hello", "Morning")
输出 :
Hello and Good Morning.
示例 3:带有 lambda 的函数
在这个例子中,第一个方法是 A() 并且第二个方法是未命名的,即;与 lambda。 A() 方法返回 lambda 语句方法,该方法保存为名称为 returned_function 的对象,并将用于调用第二个方法。
Python3
# first method that return second method
def A(u, v):
w = u + v
z = u - v
# return second method without name
return lambda: print(w * z)
# form a object of first method
# i.e; second method
returned_function = A(5, 2)
# check object
print(returned_function)
# call second method by first method
returned_function()
输出 :
. at 0x7f65d8e17158>
21