在编程中,多次调用同一个函数但使用不同的参数是一种常见且强大的技术。这允许我们重用函数逻辑来处理不同的输入数据,提高代码的复用性和可维护性。
def square(x):
return x * x
print(square(2)) # 4
print(square(3)) # 9
def add(a, b):
return a + b
print(add(1, 2)) # 3
print(add("a", "b")) # "ab"
def average(*args):
return sum(args) / len(args)
print(average(1, 2, 3)) # 2.0
print(average(5, 10)) # 7.5
原因:函数修改了外部状态或可变参数
示例:
let total = 0;
function addToTotal(x) {
total += x;
return total;
}
console.log(addToTotal(5)); // 5
console.log(addToTotal(3)); // 8 (可能不是预期行为)
解决方案:尽量编写纯函数,避免副作用
原因:调用时参数顺序与函数定义不匹配
示例:
def divide(a, b):
return a / b
print(divide(1, 2)) # 0.5
print(divide(2, 1)) # 2.0 (可能不是预期行为)
解决方案:
原因:频繁调用复杂函数导致性能下降
示例:
def expensive_calculation(x):
# 模拟耗时计算
import time
time.sleep(1)
return x * x
# 多次调用导致总执行时间长
for i in range(10):
print(expensive_calculation(i))
解决方案:
原因:未对输入参数进行充分验证
示例:
def calculate_age(birth_year):
return 2023 - birth_year
print(calculate_age(1990)) # 33
print(calculate_age(3000)) # -977 (不合理结果)
解决方案:添加参数验证
def calculate_age(birth_year):
if not 1900 <= birth_year <= 2023:
raise ValueError("Invalid birth year")
return 2023 - birth_year
function add(a) {
return function(b) {
return a + b;
}
}
const add5 = add(5);
console.log(add5(3)); // 8
console.log(add5(10)); // 15
from functools import partial
def power(base, exponent):
return base ** exponent
square = partial(power, exponent=2)
cube = partial(power, exponent=3)
print(square(5)) # 25
print(cube(3)) # 27
def flexible_function(**kwargs):
if 'name' in kwargs:
print(f"Hello, {kwargs['name']}!")
if 'age' in kwargs:
print(f"You are {kwargs['age']} years old.")
flexible_function(name="Alice", age=30)
flexible_function(name="Bob")
flexible_function(age=25)
通过合理使用不同参数的函数调用,可以大幅提高代码的灵活性和可维护性,同时需要注意相关的陷阱和最佳实践。
没有搜到相关的文章