Python——functools模块

Python的functools模块提供了多种辅助函数,用于高阶函数编程、函数装饰器以及其他高级函数操作。以下是一些functools模块中的重要函数及其简要说明和示例:

  1. partial

    • 功能:创建一个新的可调用对象,该对象预先填充了部分参数。
    • 示例:
      from functools import partial
      
      def power(base, exponent):
          return base ** exponent
      
      squared = partial(power, exponent=2)
      print(squared(3))  # 输出 9,等同于 power(3, 2)
      
      cubed = partial(power, 3)
      print(cubed())  # 输出 27,等同于 power(3, None)
      
  2. lru_cache

    • 功能:为可调用对象提供一个大小受限的Least Recently Used(LRU)缓存,优化多次调用同一输入时的性能。
    • 示例:
      from functools import lru_cache
      
      @lru_cache(maxsize=32)
      def fibonacci(n):
          if n < 2:
              return n
          return fibonacci(n - 1) + fibonacci(n - 2)
      
      print(fibonacci(30))  # 仅在首次计算时复杂,后续调用直接从缓存中取出结果
      
  3. reduce

    • 功能:对一个序列或迭代器中的元素应用二元函数,将序列缩减为单个值。
    • 示例:
      from functools import reduce
      
      numbers = [1, 2, 3, 4, 5]
      total = reduce(lambda x, y: x + y, numbers)
      print(total)  # 输出 15,等同于求和整个序列
      
  4. cmp_to_key

    • 功能:将旧式比较函数(接受两个参数并返回-1、0或1表示小于、等于或大于)转换为可用于排序的关键字函数。
    • 示例:
      from functools import cmp_to_key
      
      def compare(a, b):
          return (a > b) - (a < b)
      
      sorted_list = sorted(['apple', 'banana', 'cherry'], key=cmp_to_key(compare))
      print(sorted_list)
      
  5. total_ordering

    • 功能:类装饰器,为只定义了一部分比较方法(如__eq__, __lt__)的类补充缺失的比较方法,使其满足全序关系。
    • 示例:
      from functools import total_ordering
      
      @total_ordering
      class SimpleComparable:
          def __init__(self, value):
              self.value = value
      
          def __eq__(self, other):
              return self.value == other.value
      
          def __lt__(self, other):
              return self.value < other.value
      
      a = SimpleComparable(1)
      b = SimpleComparable(2)
      print(a <= b)  # 自动获得了__le__方法
      
  6. ** singledispatch**

    • 功能:单分发泛型函数装饰器,允许根据第一个参数的类型选择不同的实现。
    • 示例:
      from functools import singledispatch
      
      @singledispatch
      def process_data(data):
          raise TypeError('Unsupported data type')
      
      @process_data.register(str)
      def _(data: str):
          return len(data)
      
      @process_data.register(int)
      def _(data: int):
          return data * 2
      
      print(process_data('hello'))  # 输出 5
      print(process_data(10))  # 输出 20
      
  7. update_wrapper

    • 功能:用于更新函数的元信息,确保装饰器不会改变被装饰函数的名称、文档字符串等属性。
    • 示例:
      from functools import update_wrapper
      
      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 update_wrapper(wrapper, func)
      
      @my_decorator
      def example_function():
          """Example docstring."""
          print("Function body")
      
      print(example_function.__name__)  # 输出 "example_function"
      print(example_function.__doc__)  # 输出 "Example docstring."
      
  8. cached_property

    • 功能:类装饰器,用于将类属性转换成惰性计算且只计算一次的属性(仅限Python 3.8及以上版本)。
    • 示例:
      from functools import cached_property
      
      class MyClass:
          def __init__(self, value):
              self._value = value
      
          @cached_property
          def processed_value(self):
              # 这个方法只会被执行一次,之后会从缓存中取值
              return expensive_computation(self._value)
      
      obj = MyClass(10)
      print(obj.processed_value)
      
  9. 其他函数如cmp, clear_cache, get_unbound_method(在Python 3.x中不再推荐使用)等,随着Python版本的演进,一些函数已被移除或替换,所以这里没有列出。

请注意,随着时间的推移,Python标准库中的functools模块可能会增加或删除某些函数。上面的示例基于较新版本的Python语言规范,建议查阅Python官方文档以获取最新和完整的模块信息。

  • 15
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值