Home / Programs / Python Decorators - 2 - Hands On
🚀 Programming Example

Python Decorators - 2 - Hands On

👁 511 Views
💻 Practical Program
📘 Step Learning

Python Decorators - 2 - Hands On

📌 Information & Algorithm

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 Code

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

                        

🖥 Program Output

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

Master Programming Through Practical Examples

Improve your coding logic, problem-solving skills and programming confidence by practicing real-world examples with explanations.

🎯 How to learn from this example

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.

🔥 Practice suggestion

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.