一、 介绍
在Python中,partial function(偏函数)是一种很有用的函数,它能够减轻我们使用每个函数时所需要传入的所有参数的负担,从而使代码更加干净、紧凑和可维护。在本文中,我们将详细介绍Python中偏函数的使用,以及如何使用它们来改善我们的代码。
二、 什么是偏函数?
当我们使用函数时,我们经常需要在每次调用该函数时传递所有参数。但有时我们可能只想传递其中的一些参数,而其他参数可以使用默认值。这时,Python偏函数就派上用场了。 换句话说,partial function 通过预先设置函数的某些参数来创建一个新函数。这个新函数只需要接收未预设的那些参数即可。
三、 偏函数在Python中的使用
1. functools.partial(function, *args, **keywords)
Python中偏函数的标准库是functools.partial
。下面是一个很简单的例子:
import functools
def add(a, b):
return a + b
increment = functools.partial(add, b=1)
print(increment(3))
这里,我们将add
函数中的第二个参数b
设置为1
,从而获得一个新函数increment
。 like
2. 类方法的partial function
同样的,我们可以使用偏函数改进类方法,下面的例子中我们使用类方法和偏函数去改进数据生成的方法。
import functools
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
@classmethod
def create_square(cls, length):
return cls(length, length)
Square = functools.partial(Rectangle, height=5)
square = Square(width=10)
print(square.area())
3. 使用偏函数绑定方法
我们也可以使用偏函数装饰方法,下面是一些示例:
import functools
class Person:
def __init__(self, firstname, lastname):
self.firstname = firstname
self.lastname = lastname
def get_name(self, separator=" "):
return self.firstname + separator + self.lastname
person = Person("John", "Doe")
get_fullname = functools.partial(person.get_name, separator=".")
print(get_fullname()) # John.Doe
get_lastname = functools.partial(person.get_name, separator=", ")
print(get_lastname()) # John, Doe
4. 高阶函数与偏函数
我们可能已经分析过如何发挥Python中的高阶函数的威力,将函数传递给函数并处理结果。然而,与偏函数结合使用时,我们甚至可以进一步减少对程序的代码量
import functools
def running_total(numbers):
return functools.reduce(lambda a, x: a + x, numbers)
numbers = [1,2,3,4,5]
partial_sum = functools.partial(running_total, numbers)
print(partial_sum()) # 15
numbers.append(6)
print(partial_sum()) # 21
四、 总结
Python的偏函数为我们提供了一种清晰、简洁、可读以及可维护的API来装饰我们的代码。它们可以大大减少不必要的重复代码,使我们的代码变得更加简洁和可读。