
01 偏函数
当函数的参数个数太多,需要简化时,使用functools.partial可以创建一个新的函数,这个新函数可以固定住原函数的部分参数,从而在调用时更简单。
from functools import partialdef func(a1,a2,a3):print(a1,a2,a3)new_func1 = partial(func,a1=1,a2=2)new_func1(a3=3)new_func2 = partial(func,1,2)new_func2(3)new_func3 = partial(func,a1=1)new_func3(a2=2,a3=3)
注意:partial括号内第一个参数是原函数,其余参数是需要固定的参数
效果图:
02 __add__的使用
如果一个类里面定义了 __add__方法,如果这个类的对象 +另一个对象,会触发这个类的__add__方法,换个说法如果 对象1+对象2 则会触发对象1的 __add__方法,python在类中有很多类似的方法,对象会在不同情况下出发对应的方法。
class Foo:def __init__(self):self.num = 1def __add__(self, other):if isinstance(other,Foo):result = self.num + other.numelse:result = self.num + otherreturn resultfo1 = Foo()fo2 = Foo()v1 = fo1 + fo2v2 = fo1 + 4print(v1,v2)
03 chain函数
chain函数来自于itertools库,itertools库提供了非常有用的基于迭代对象的函数,而chain函数则是可以串联多个迭代对象来形成一个更大的迭代对象 。
实例1:
from itertools import chainl1 = [1,2,3]l2 = [4,5]new_iter = chain(l1,l2) # 参数必须为可迭代对象print(new_iter)for i in new_iter:print(i)
效果图:
实例2:
from itertools import chaindef f1(x):return x+1def f2(x):return x+2def f3(x):return x+3list_4 = [f1, f2]new_iter2 = chain([f3], list_4)for i in new_iter2:print(i)
效果图:
