Advanced a python (functional programming) [1-9] Function of Partial python

partial function in python

When a function has many parameters, the caller will need more than one parameter. If you reduce the number of parameters, you can simplify the burden on the caller.

For example, int () function can convert the string to an integer only when an incoming string, int () function default decimal conversion:

>>> int('12345')
12345

However, int () function also provides additional base parameters, the default value is 10. If the incoming base parameters, you can do the N-ary conversion:

1 >>> int('12345', base=8)
2 5349
3 >>> int('12345', 16)
4 74565

Suppose you want to convert a large number of binary string, each incoming int (x, base = 2) is very difficult, so we thought, you can define a function int2 (), the default pass in the base = 2:

1 def int2(x, base=2):
2     return int(x, base)

In this way, we convert the binary is very convenient:

>>> int2('1000000')
64
>>> int2('1010101')
85

functools.partial is to help us create a partial function, do not need our own definition int2 (), you can directly use the following code to create a new function int2:

>>> import functools
>>> int2 = functools.partial(int, base=2)
>>> int2('1000000')
64
>>> int2('1010101')
85

So, functools.partial can be a function of many parameters become less of a new parameter function, fewer parameters need to specify a default value when you create, so the difficulty of the new function calls is reduced.

task

In Section 7, we pass the custom sorting function in this sorted order functions can be achieved in the sort ignore case. Please functools.partial this complex into a simple function call:

1 import functools
2 sorted_ignore_case = functools.partial(sorted, cmp=lambda s1, s2: cmp(s1.upper(), s2.upper()))
3 print sorted_ignore_case(['bob', 'about', 'Zoo', 'Credit'])

 

Guess you like

Origin www.cnblogs.com/ucasljq/p/11622294.html