使用 functools.partial
可以建立一個新的函數,這個新函數可以固定住原函數的部分參數,進而在調用時更簡單。
# -*- coding: utf-8 -*-
# @File : partial偏函數.py
# @Date : 2018-05-30
# @Author : Peng Shiyu
from functools import partial
# 預設按十進制轉換
r1 = int("12")
print(r1, type(r1))
# 12 <class 'int'>
# 按二進制轉換
r2 = int("0101", base=2)
print(r2, type(r2))
# 5 <class 'int'>
# 使用偏函數, 改造原有的int函數
int2 = partial(int, base=2)
r3 = int2("0101")
print(r3, type(r3))
# 5 <class 'int'>