定义函数
使用`def`关键字定义一个函数,例如:
def greet(name):
print("Hello, " + name)
匿名函数
使用`lambda`关键字创建一个匿名函数,例如:
func = lambda x, y: x + y
print(func(3, 4)) 输出 7
函数作为参数传递
函数可以作为参数传递给其他函数,例如:
def test(f, a, b):
print('test')
print(f(a, b))
test(func, 3, 5) 输出 8
使用内置函数
使用内置函数,如`map`,可以传递函数对象作为参数,例如:
re = map(lambda x: x + 3, [1, 3, 5, 6])
print(list(re)) 输出 [4, 6, 8, 9]
返回函数
函数可以返回另一个函数,例如:
def create_adder(n):
return lambda x: x + n
adder_3 = create_adder(3)
print(adder_3(10)) 输出 13
装饰器
函数对象可以用作装饰器,用于修改或增强函数的行为,例如:
def my_decorator(func):
def wrapper(*args, kwargs):
print("Something is happening before the function is called.")
func(*args, kwargs)
print("Something is happening after the function is called.")
return wrapper
@my_decorator
def say_hello(name):
print("Hello, " + name)
say_hello("Alice") 输出:
Something is happening before the function is called.
Hello, Alice
Something is happening after the function is called.
这些是Python中函数对象的基本用法。您可以根据需要选择使用这些方法来创建和使用函数对象