Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

python高阶函数

作者:诸神之翼   发布日期:2026-03-09   浏览:88

# 示例代码:Python高阶函数

# 高阶函数是指可以接收函数作为参数,或者返回值为函数的函数。

# 1. 接收函数作为参数的高阶函数示例
def apply_operation(operation, a, b):
    return operation(a, b)

# 定义一些简单的操作函数
def add(x, y):
    return x + y

def subtract(x, y):
    return x - y

# 使用高阶函数
result_add = apply_operation(add, 5, 3)
result_subtract = apply_operation(subtract, 5, 3)

print("Addition result:", result_add)  # 输出: Addition result: 8
print("Subtraction result:", result_subtract)  # 输出: Subtraction result: 2


# 2. 返回函数作为结果的高阶函数示例
def make_multiplier(factor):
    def multiplier(x):
        return x * factor
    return multiplier

# 创建两个不同的乘法器
double = make_multiplier(2)
triple = make_multiplier(3)

print("Double of 5:", double(5))  # 输出: Double of 5: 10
print("Triple of 5:", triple(5))  # 输出: Triple of 5: 15

解释说明:

  1. 接收函数作为参数的高阶函数apply_operation 函数接收一个操作函数 operation 和两个参数 ab,然后调用 operation(a, b) 来执行相应的操作。这里我们定义了两个简单的操作函数 addsubtract,分别用于加法和减法。

  2. 返回函数作为结果的高阶函数make_multiplier 函数接收一个 factor 参数,并返回一个新的函数 multiplier,该函数会将传入的参数 x 乘以 factor。通过这种方式,我们可以创建多个不同的乘法器(如 doubletriple),它们的行为取决于 make_multiplier 中传递的 factor 值。

上一篇:python linearregression

下一篇:python onnx

大家都在看

python 二维码识别

python excel 库

python时间格式

pythoneval函数用法

列表切片操作python

python读取文件路径

staticmethod在python中有

python 保存json文件

python开发windows应用程序

python中len是什么意思

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站