Python Decorators

Python Decorators :

A decorator in Python is a way to modify or add functionality to a function without changing its code. It uses the @ symbol to apply extra behavior to a function.


Syntax :

@decorator_name
def function_name():
    # Function code


Example :

# Define a decorator
def greet_decorator(func):
    def wrapper():
        print("Good Morning!")  # Extra behavior added
        func()  # Call the original function
    return wrapper

# Apply the decorator using @
@greet_decorator
def say_hello():
    print("Hello, how are you?")

# Call the function
say_hello()


Output:

Good Morning!
Hello, how are you?

Post a Comment

0 Comments