Python Decorators - 2 - Hands On
Python Decorators - 2 - Hands On
Python Decorators - 2 - Hands On
2. Decorators - 2
1. Decorate the average function with the log decorator as shown in the following code.
2. Execute and verify if the log decorator is able to write the log to STDOUT.
@log
def average (n1,n2, n3): return (n1+n2+n3)/3
3. Use the Test against custom input box to output the result for debugging.
4. Provide integer/float values (refer test case samples) to display the output/error.
3,8,16
Accessed the function -'average' with arguments (3.0, 8.0, 16.0) {}
9.0
#!/bin/python3
import sys
import os
def log(func):
def inner(*args, **kwdargs):
str_template = "Accessed the function -'{}' with arguments {} {}".format(func.__name__,
args,
kwdargs)
return str_template + "\n" + str(func(*args, **kwdargs))
return inner
#Add greet function definition here
@log
def average(n1,n2,n3):
return (n1+n2+n3)/3
'''Check the Tail section for input/output'''
if __name__ == "__main__":
with open(os.environ['OUTPUT_PATH'], 'w') as fout:
res_lst = list()
(a,b,c) = (map(lambda x: float(x.strip()), input().split(',')))
res_lst.append(average(a,b,c))
fout.write("{}".format(*res_lst))
Accessed the function -'average' with arguments (8.0, 2.4, 4.6) {}
5.0
First understand the algorithm carefully. Then study the program line-by-line and compare it with the output. Finally, review the explanation section to strengthen your logic and programming understanding.
Rewrite the program without looking at the code. Modify values, conditions or logic and run it again. This helps improve confidence and strengthens coding skills much faster.