Home Python Programming Language / Programs / Python Decorators - 1 - Hands On
🚀 Programming Example

Python Decorators - 1 - Hands On

👁 646 Views
💻 Practical Program
📘 Step Learning

Python Decorators - 1 - Hands On

No previous program
No next program

📌 Information & Algorithm

1. Decorators - 1

1. Define a decorator function log which logs information about a function and the arguments passed to it.

2. Ensure that the log message is written to STDOUT.

3. Use the Test against custom input box to output the result for debugging.

4. Provide a text string (refer test case samples) to display the output/error.

Given Input:

hello world!

Expected Output:

Accessed the function -'greet' with arguments ('hello world!',) {}

💻 Program Code

#!/bin/python3
import sys
import os
import datetime as dt

#Add log function and inner function implementation here

def log(func):

    def inner(*args, **kwdargs):

        STDOUT= "Accessed the function -'{}' with arguments {} {}".format(func.__name__,args,kwdargs)

        return STDOUT

    return inner


def greet(msg):

    'Greeting Message : ' + msg

    

greet = log(greet)
    

'''Check the Tail section for input/output'''

if __name__ == "__main__":
    with open(os.environ['OUTPUT_PATH'], 'w') as fout:
        res_lst = list()
        res_lst.append(greet(str(input())))
        fout.write("{}".format(*res_lst))

                        

🖥 Program Output

Accessed the function -'greet' with arguments ('Python is awesome',) {}
                            
No previous program
No next program
📚 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.