1. 程式人生 > >偏函式(Partial)

偏函式(Partial)

偏函式可以實現兩種功能

1、對引數進行補充,共同處理

# /usr/bin/env Python3
# -*- encoding:UTF-8 -*-
# test.py
from functools import partial
def sum(*args):
    s = 0
    for n in args:
        print(n)
    return s

sum_add_10 = partial(sum,10)
sum_add_10_20 = partial(sum,10,20)
# print("--------原函式sum的函式地址入口")
# print(sum)
# print("--------paritial函式的入口地址")
# print(partial(sum,10)) print(sum(1,2,3)) print(sum_add_10(1,2,3)) print(sum_add_10_20(1,2,3))

2、替換下引數的值,便於除錯

import functools

def mod(m,*,key = 2):
    return m % key == 0

mod_to_2 = functools.partial(mod,key = 3)

print(mod(3))
print(mod_to_2(3))