Flask上下文源码阅读前戏

06.Flask上下文源码阅读前戏

偏函数

当函数的参数个数太多,需要简化时,使用functools.partial可以创建一个新的函数,这个新函数可以固定住原函数的部分参数,从而在调用时更简单。

from functools import partial


def 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)
'''
1 2 3
1 2 3
1 2 3
'''

注意:partial括号内第一个参数是原函数,其余参数是需要固定的参数

__add__的使用

如果一个类里面定义了 __add__方法,如果这个类的对象 +另一个对象,会触发这个类的__add__方法,换个说法如果 对象1+对象2 则会触发对象1__add__方法,python在类中有很多类似的方法,对象会在不同情况下出发对应的方法。

class Foo:
    def __init__(self):
        self.num = 1
    def __add__(self, other):
        if isinstance(other,Foo):
            result = self.num + other.num
        else:
            result = self.num + other
        return result

fo1 = Foo()
fo2 = Foo()
v1 = fo1 + fo2
v2 = fo1 + 4
print(v1,v2)

chain函数

chain函数来自于itertools库,itertools库提供了非常有用的基于迭代对象的函数,而chain函数则是可以串联多个迭代对象来形成一个更大的迭代对象 。

实例1:

from itertools import chain

l1 = [1,2,3]
l2 = [4,5]

new_iter = chain(l1,l2) # 参数必须为可迭代对象
print(new_iter)
for i in new_iter:
    print(i)
'''
1
2
3
4
5
'''

实例2:

from itertools import chain


def f1(x):
    return x+1

def f2(x):
    return x+2

def f3(x):
    return x+3
list_4 = [f1, f2]
new_iter2 = chain([f3], list_4)
for i in new_iter2:
    print(i)
'''
<function f3 at 0x00000210FF544CA0>
<function f1 at 0x00000210F04661F0>
<function f2 at 0x00000210F0A3A0D0>
'''
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

贾维斯Echo

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值