InterviewSolution
| 1. |
What is a partial object in Python? |
|
Answer» ALTHOUGH Python is predominantly an object oriented programming language, it does have important functional programming capabilities INCLUDED in functools module. One such function from the functools module is partial() function which returns a partial object. The object itself behaves like a function. The partial() function receives another function as argument and freezes some portion of a function’s arguments resulting in a new object with a simplified signature. Let us consider the signature of built-in int() function which is as below: int(x, base=10)This function converts a number or string to an integer, or returns 0 if no arguments are GIVEN. If x is a number, returns x.__int__(). For floating point numbers, this truncates towards zero. If x is not a number or if base is given, then x must be a string. >>> int(20) 20 >>> int('20', base=8) 16We now use partial() function to create a callable that behaves like the int() function where the base argument defaults to 8. >>> from functools import partial >>> partial_octal=partial(int,base=8) >>> partial_octal('20') 16In the following example, a user defined function power() is used as argument to a partial function square() by setting a default value on one of the arguments of the original function. >>> def power(x,y): return x**y >>> power(x=10,y=3) 1000 >>> square=partial(power, y=2) >>> square(10) 100The functools module also defines partialmethod() function that returns a new partialmethod DESCRIPTOR which behaves like partial except that it is designed to be used as a method definition rather than being directly callable. |
|