编写根据参数执行不同计算的函数的最佳方法是什么?

Jaf*_*XXI 4 python if-statement function

我只想知道编写编写根据参数执行不同计算的函数的最佳方法是什么。

举一个非常简单的例子,假设我想要一个函数,该函数可以将两个数字相乘或相除,具体取决于仅取两个值的参数值“乘”或“除”。我要做的是这样的:

def simple_operation(a, b, operation):
    if operation == 'divide':
        return a / b
    elif operation == 'multiply':
        return a * b


print(simple_operation(3, 9, 'multiply'))
Run Code Online (Sandbox Code Playgroud)

在我的特定情况下,我想根据温度计算反应的平衡常数,并且有不同的方法可以做到这一点。例如,使用van't Hoff方程或计算特定温度下的地层性质。每种方式(都有优点和缺点)都需要大量的行,所以我不知道什么是最好的方法,我觉得可能有比使用if语句处理每种情况的代码更多的方法。我想知道经验丰富的程序员如何处理这种情况。

Net*_*ave 5

使用dict

def simple_operation(a, b, operation):
    operations = {
        'divide'  : lambda a, b: a / b,
        'multiply': lambda a, b: a * b,
    }
    return operations.get(operation)(a, b)
Run Code Online (Sandbox Code Playgroud)

您可以为未知操作添加默认功能:

def simple_operation(a, b, operation):
        def err(*_):
            raise ValueError("Operation not accepted")
        operations = {
            'divide'  : lambda a, b: a / b,
            'multiply': lambda a, b: a * b,
        }
        return operations.get(operation, err)(a, b)
Run Code Online (Sandbox Code Playgroud)

您可以在字典中引用任何内容,最好使用纯函数而不是lambda或operator模块:

import operator
def simple_operation(a, b, operation):
        def err(*_):
            raise ValueError("Operation not accepted")
        operations = {
            'divide'  : operator.truediv,
            'multiply': operator.mul,
        }
        return operations.get(operation, err)(a, b)
Run Code Online (Sandbox Code Playgroud)