Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Cách truyền hàm Python làm đối số cho hàm khác

Python hỗ trợ first-class functions: hàm có thể truyền như biến thường.

Ví dụ với map()

def sqr(x):
    return x ** 2

s = [1, 3, 5, 7, 9]
print(list(map(sqr, s)))  # [1, 9, 25, 49, 81]

Dùng lambda

print(list(map(lambda x: x**2, s)))  # [1, 9, 25, 49, 81]

Custom higher-order function

def apply_twice(func, arg):
    return func(func(arg))

def add_five(x):
    return x + 5

print(apply_twice(add_five, 10))  # 20 (10+5+5)

Decorator pattern

def my_decorator(func):
    def wrapper(*args, **kwargs):
        print("Before call")
        result = func(*args, **kwargs)
        print("After call")
        return result
    return wrapper

@my_decorator
def say_hello():
    print("Hello!")

say_hello()
# Before call
# Hello!
# After call

Ứng dụng: callbacks, event handlers, strategy pattern, decorators, functional programming (map, filter, reduce).