You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将长代码改写为以加减运算符为参数的Python函数?

How to Pass + and - Operators as Function Arguments in Python

Hey Sara, nice to see you working on refactoring your code to cut down repetition—smart move! Passing arithmetic operators as function arguments is totally doable in Python, and there are a couple of clean ways to pull it off. Let me break this down for you.

Core Idea

In Python, operators like + and - aren't just symbols—they map to callable functions (or can be represented with simple lambdas). We can pass these callable objects directly to our function, which lets us reuse all your existing lengthy code logic while swapping out only the operation itself.

Method 1: Use the operator Module (Cleanest Approach)

The standard library's operator module has ready-made functions for all basic arithmetic operations, so you don't have to reinvent the wheel.

Step 1: Wrap Your Lengthy Code into a Reusable Function

Let’s assume your original repetitive code looks something like this:

# Original repetitive code example
value_a = 35
value_b = 12

# Addition scenario (with all your shared lengthy logic)
print(f"Calculation result: {value_a + value_b}")
# ... 10+ lines of other fixed code (validation, logging, formatting, etc.)

# Subtraction scenario (same lengthy logic repeated)
print(f"Calculation result: {value_a - value_b}")
# ... same 10+ lines of code copied again

We can refactor all that shared logic into a single function that accepts an operation parameter:

import operator

def execute_calculation(val1, val2, operation):
    # Paste all your original lengthy code logic here
    # Example shared steps: input validation, logging, result formatting
    if not isinstance(val1, (int, float)) or not isinstance(val2, (int, float)):
        raise TypeError("Inputs must be numbers!")
    
    # Run the passed operation
    result = operation(val1, val2)
    
    # More shared logic (e.g., formatting the output)
    final_output = f"Completed calculation: {result:.2f}"
    print(final_output)
    
    return result

Step 2: Call the Function with Different Operators

Now you can reuse the entire function with just the operator changed:

# Use addition
execute_calculation(35, 12, operator.add)  # Output: Completed calculation: 47.00

# Use subtraction
execute_calculation(35, 12, operator.sub)  # Output: Completed calculation: 23.00

Method 2: Use Lambda Functions (No Imports Needed)

If you’d rather avoid importing the operator module, you can define simple lambdas to represent the operations:

def execute_calculation(val1, val2, operation):
    # Same shared lengthy logic as before
    if not isinstance(val1, (int, float)) or not isinstance(val2, (int, float)):
        raise TypeError("Inputs must be numbers!")
    
    result = operation(val1, val2)
    final_output = f"Completed calculation: {result:.2f}"
    print(final_output)
    
    return result

# Addition with lambda
execute_calculation(22, 9, lambda x, y: x + y)  # Output: Completed calculation: 31.00

# Subtraction with lambda
execute_calculation(22, 9, lambda x, y: x - y)  # Output: Completed calculation: 13.00

Bonus: Scale to Other Operations Later

This pattern works for any arithmetic operation—if you need multiplication or division down the line, just pass operator.mul/operator.truediv or a corresponding lambda. No need to rewrite all your shared lengthy code!

Let me know if you need help adapting this to fit your exact code structure.

内容的提问来源于stack exchange,提问作者Sara

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:11:58