Code Explanation:
1. Import partial
from functools import partial
functools is a built-in Python module.
partial is a function available inside functools.
It is used to fix some arguments of an existing function and create a new function.
2. Define the calc() Function
def calc(a, b, c):
Here, we create a function named calc.
It accepts three parameters:
a
b
c
For example:
calc(2, 4, 5)
means:
a = 2
b = 4
c = 5
3. Perform the Calculation
return a * b + c
The function calculates:
a × b + c
For example:
2 × 4 + 5
= 8 + 5
= 13
4. Create a Partial Function
f = partial(calc, 2, c=5)
⭐ This is the most important line.
partial() creates a new function from calc() while fixing some arguments.
Here:
a = 2
c = 5
are fixed.
Only b needs to be supplied later.
So we can think of f as:
f(b) → calc(2, b, 5)
5. First Function Call
x = f(4)
The 4 becomes the remaining parameter b.
Therefore:
a = 2
b = 4
c = 5
Now calculate:
2 × 4 + 5
= 8 + 5
= 13
Therefore:
x = 13
6. Second Function Call
y = f(10)
Again, a and c are already fixed.
a = 2
b = 10
c = 5
Calculation:
2 × 10 + 5
= 20 + 5
= 25
Therefore:
y = 25
7. Print the Values
print(x, y)
At this point:
x = 13
y = 25
So the output is:
13 25
๐ Internal Working
This:
f = partial(calc, 2, c=5)
can conceptually be understood as:
Original:
calc(a, b, c)
Fixed:
a = 2
c = 5
Remaining:
b
Therefore:
f(4)
↓
calc(2, 4, 5)
↓
13
and:
f(10)
↓
calc(2, 10, 5)
↓
25
๐ Execution Table
Expression a b c Result
f(4) 2 4 5 13
f(10) 2 10 5 25
๐ง Key Concept
partial() pre-fills arguments of a function.
Instead of repeatedly writing:
calc(2, 4, 5)
calc(2, 10, 5)
we fix the common arguments once:
f = partial(calc, 2, c=5)
and then provide only the changing argument:
f(4)
f(10)
๐ฏ Final Output
13 25

0 Comments:
Post a Comment