Python Decorators - 2 - Hands On

Python Python Classes and Objects (Article) Python Classes and Objects (Program)

420

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.

Given Input:

3,8,16

Expected Output:

Accessed the function -'average' with arguments (3.0, 8.0, 16.0) {}
9.0

Program:

 #!/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))

Output:

Accessed the function -'average' with arguments (8.0, 2.4, 4.6) {}
5.0

This Particular section is dedicated to Programs only. If you want learn more about Python. Then you can visit below links to get more depth on this subject.