📝 面试求职: 「面试试题小程序」 ,内容涵盖 测试基础、Linux操作系统、MySQL数据库、Web功能测试、接口测试、APPium移动端测试、Python知识、Selenium自动化测试相关、性能测试、性能测试、计算机网络知识、Jmeter、HR面试,命中率杠杠的。(大家刷起来…)
📝 职场经验干货:
functools 是 Python 标准库中非常强大的模块,提供了一系列用于函数式编程的工具函数。它主要用于增强或操作可调用对象(如函数),提升代码的复用性和可读性。
✅ 1. functools.reduce(function, iterable[, initializer])
功能:
对可迭代对象中的元素进行累积计算(归约)。
from functools import reduce
# 累加所有数字
result = reduce(lambda x, y: x + y, [1, 2, 3, 4])
print(result) # 输出: 10
# 使用初始值
result = reduce(lambda x, y: x + y, [1, 2, 3], 10)
print(result) # 输出: 16
✅ 2. functools.partial(func, *args, **keywords)
功能:
固定函数的部分参数,返回一个新的部分应用函数(Partial Application)。
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(5)) # 输出: 125
✅ 3. functools.lru_cache(maxsize=128)
功能:
缓存函数结果,避免重复计算,常用于递归或耗时函数。
📌 适用于幂等函数(相同输入始终输出相同结果)
from functools import lru_cache
@lru_cache(maxsize=None) # 不限制缓存大小
def fib(n):
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
print(fib(100)) # 非常快,因为中间结果被缓存了
✅ 4. functools.wraps(wrapped, assigned=WRAPPER_ASSIGNMENTS, updated=WRAPPER_UPDATES)
功能:
保留装饰器包裹函数的元信息(如 __name__, __doc__),推荐在写装饰器时使用。
from functools import wraps
def my_decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
print("Before function call")
result = func(*args, **kwargs)
print("After function call")
return result
return wrapper
@my_decorator
def say_hello():
"""Greet the user."""
print("Hello")
print(say_hello.__name__) # 输出: say_hello(而不是 wrapper)
print(say_hello.__doc__) # 输出: Greet the user.
✅ 5. functools.total_ordering()
功能:
为类自动生成比较方法(<, <=, >, >=),只需定义 __eq__ 和一个其他比较方法即可。
from functools import total_ordering
@total_ordering
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __eq__(self, other):
return self.age == other.age
def __lt__(self, other):
return self.age < other.age
p1 = Person("Alice", 30)
p2 = Person("Bob", 25)
print(p1 > p2) # True
print(p1 < p2) # False
✅ 6. functools.cmp_to_key(func)
功能:
将旧式的比较函数(返回 -1, 0, 1)转换为可用于 sorted() 的 key 函数。
from functools import cmp_to_key
def compare(a, b):
if a < b:
return -1
elif a > b:
return 1
else:
return 0
nums = [5, 2, 9, 1]
sorted_nums = sorted(nums, key=cmp_to_key(compare))
print(sorted_nums) # 输出: [1, 2, 5, 9]
✅ 7. functools singledispatch
功能:
根据第一个参数的类型进行函数重载(多态函数)。
from functools import singledispatch
@singledispatch
def process(data):
print("默认处理:", data)
@process.register(int)
def _(data):
print("处理整数:", data * 2)
@process.register(str)
def _(data):
print("处理字符串:", data.upper())
process(10) # 输出: 处理整数: 20
process("abc") # 输出: 处理字符串: ABC
process([1,2]) # 输出: 默认处理: [1, 2]
✅ 8. functools.cache (Python 3.9+)
功能:
类似于 lru_cache(None),但更高效,适合无参或不可变参数的函数。
from functools import cache
@cache
def factorial(n):
if n <= 1:
return 1
return n * factorial(n - 1)
print(factorial(100)) # 快速计算,且不会重复计算
✅ 总结表格:常用 functools 工具函数一览
最后: 下方这份完整的软件测试视频教程已经整理上传完成,需要的朋友们可以自行领取【保证100%免费】