在Python中将函数作为参数传递
一个函数可以接受多个参数,这些参数可以是对象、变量(相同或不同的数据类型)和函数。 Python函数是一流的对象。在下面的示例中,将函数分配给变量。此分配不调用函数。它获取由喊叫引用的函数对象并创建指向它的第二个名称,叫喊。
# Python program to illustrate functions
# can be treated as objects
def shout(text):
return text.upper()
print(shout('Hello'))
yell = shout
print(yell('Hello'))
输出:
HELLO
HELLO
高阶函数
因为函数是对象,我们可以将它们作为参数传递给其他函数。可以接受其他函数作为参数的函数也称为高阶函数。在下面的示例中,创建了一个以函数作为参数的函数greet。
# Python program to illustrate functions
# can be passed as arguments to other functions
def shout(text):
return text.upper()
def whisper(text):
return text.lower()
def greet(func):
# storing the function in a variable
greeting = func("Hi, I am created by a function passed as an argument.")
print(greeting)
greet(shout)
greet(whisper)
输出
HI, I AM CREATED BY A FUNCTION PASSED AS AN ARGUMENT.
hi, i am created by a function passed as an argument.
包装函数
包装函数或装饰器允许我们包装另一个函数以扩展被包装函数的行为,而无需永久修改它。在装饰器中,函数被作为参数传入另一个函数,然后在包装函数内部调用。要了解有关装饰器的更多信息,请单击此处。
下面是一个简单的装饰器的例子。
# defining a decorator
def hello_decorator(func):
# inner1 is a Wrapper function in
# which the argument is called
# inner function can access the outer local
# functions like in this case "func"
def inner1():
print("Hello, this is before function execution")
# calling the actual function now
# inside the wrapper function.
func()
print("This is after function execution")
return inner1
# defining a function, to be called inside wrapper
def function_to_be_used():
print("This is inside the function !!")
# passing 'function_to_be_used' inside the
# decorator to control its behavior
function_to_be_used = hello_decorator(function_to_be_used)
# calling the function
function_to_be_used()
输出:
Hello, this is before function execution
This is inside the function !!
This is after function execution
Lambda 包装函数
在Python中,匿名函数意味着函数没有名称。我们已经知道def
关键字用于定义普通函数,而lambda
关键字用于创建匿名函数。这个函数可以有任意数量的参数,但只有一个表达式,它被计算并返回。 Lambda函数也可以有另一个函数作为参数。下面的示例显示了一个基本的 lambda函数,其中另一个 lambda函数作为参数传递。
# Defining lambda function
square = lambda x:x * x
# Defining lambda function
# and passing function as an argument
cube = lambda func:func**3
print("square of 2 is :"+str(square(2)))
print("\nThe cube of "+str(square(2))+" is " +str(cube(square(2))))
输出:
square of 2 is :4
The cube of 4 is 64