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

时间:2019-05-03 07:19:08

标签: python function if-statement

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

作为一个非常简单的示例,让我说一个函数,该函数根据参数的值乘以或除以两个数,该参数应仅取两个值“乘”或“除”。我要做的是这样的:

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


print(simple_operation(3, 9, 'multiply'))

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

2 个答案:

答案 0 :(得分: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)

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

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)

您可以在字典中引用任何内容,最好使用纯函数而不是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)

答案 1 :(得分:2)

您可以使用operator模块来传递要操作的功能 您可以使用自定义字典将字符串映射到操作员模块的相关功能,也可以使用此方法摆脱simple_operation包装器

from operator import *

#Dictionary to map user input to operation
op_map = {'divide': truediv, 'multiply': mul, 'addition': add}

#Get user input and call functions directly
print(op_map['divide'](9, 3))
#3.0
print(op_map['multiply'](9, 3))
#27
print(op_map['addition'](9, 3))
#12

作为一个额外的步骤,我继续写了用户输入部分

from operator import *

#Dictionary to map user input to operation
op_map = {'divide': truediv, 'multiply': mul, 'addition': add}

operation = input('Enter what operation you want to perform, available are divide, multiply and addition>>')
if operation not in op_map.keys():
    print('You entered an invalid operation')
    exit()
else:
    op1 = int(input('Provide the first operand>>'))
    op2 = int(input('Provide the second  operand>>'))
    res = op_map[operation](op1, op2)
    print('Result of operation {} between {} and {} is {}'.format(operation, op1, op2, res))

输出看起来像

Enter what operation you want to perform, available are divide, multiply and addition>>addition
Provide the first operand>>3
Provide the second   operand>>9
Result of operation addition between 3 and 9 is 12

Enter what operation you want to perform, available are divide, multiply and addition>>divide
Provide the first operand>>27
Provide the second   operand>>3
Result of operation divide between 27 and 3 is 9.0

正如OP所提到的,使用复杂功能的一种方法可能如下所示:

#A complex function
def complex(a,b,c,d):

    return (a/b)+(c*d)

#Dictionary to map user input to operation
op_map = {'complex': complex}

print(op_map['complex'](9, 3, 6, 4))
#27.0