What will happen if we pass the number 4
first, and 16
after? The answer will be 0.25
. But we don't want it to happen. We want a scenario where if we see that first < second
, we swap the numbers and divide them. But we aren't allowed to change the function.
Let's create a decorator that will take the function as a parameter. This decorator will add the swipe functionality to our function.
PYTHON
1def swipe_decorator(func):
2 def swipe(first, second):
3 if first < second:
4 first, second = second, first
5 return func(first, second)
6
7 return swipe
Now we have generated a decorator for the divide()
function. Let's see how it works.
PYTHON
1divide = swipe_decorator(divide)
2divide(4, 16)
The output is:
PYTHON
1The result is: 4.0
We have passed the function as a parameter to the decorator. The decorator "swiped our values" and returned the function with swiped values. After that, we invoked the returned function to generate the output as expected.
xxxxxxxxxx
14
def divide(first, second):
print ("The result is:", first/second)
def swipe_decorator(func):
def swipe(first, second):
if first < second:
first, second = second, first
return func(first, second)
return swipe
divide = swipe_decorator(divide)
divide(4, 16)
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment