python

python 偏函数

2020-06-13  本文已影响0人  wit92
Python 3.7.0 (default, Jun 28 2018, 13:15:42) 
[GCC 7.2.0] :: Anaconda, Inc. on linux
Type "help", "copyright", "credits" or "license" for more information.
1.通常的用法是在原函数声明的参数中,从前往后连续将参数值固定:
>>> from functools import partial
>>> def test_partial(a, b, c, d):
...     print(a,b,c,d)
... 
>>> test1 = partial(test_partial,1,2)
>>> test1(3,4)
1 2 3 4
>>> test2 = partial(test_partial,1,2,3,4)
>>> test2()
1 2 3 4
>>> test2(3)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: test_partial() takes 4 positional arguments but 5 were given


2.新的使用方法
1).使用关键字参数)
>>> test3 = partial(test_partial, d=4)
>>> test3(1,2,3)
1 2 3 4
2)限制
>>> test4 = partial(test_partial, c=3, d=4)
>>> test4(1,2)
1 2 3 4
>>> test5 = partial(test_partial, b=2, d=4)
>>> test5(1,3)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: test_partial() got multiple values for argument 'b'
>>> test5(a=1,c=3)
1 2 3 4
>>> test5(1,c=3)
1 2 3 4

注意:

原来的logger是有缺陷的, 需要重新写logger

上一篇 下一篇

猜你喜欢

热点阅读