Decorators in Pythons | easy way to learn about decorators

Python Decorators - Easy Explanation with Example

What are Python Decorators?

In simple terms, Python decorators allow you to modify or enhance the behavior of functions or methods without directly changing their code. They act like wrappers that provide extra functionality around your original function.

Example: Say Hello Function

Let's take a simple function that says hello:

def say_hello():
    print("Hello!")

Now, imagine you want to add something extra, like printing "Start" before saying hello and "End" after, without modifying the original say_hello function. This is where decorators come in.

Creating a Decorator

Here's how you can create a simple decorator:

def my_decorator(func):
    def wrapper():
        print("Start")
        func()  # Calls the original say_hello function
        print("End")
    return wrapper

Now, apply this decorator to the say_hello function using @my_decorator:

@my_decorator
def say_hello():
    print("Hello!")

What happens when you call the function?

When you call say_hello(), it will now print:

Start
Hello!
End

Explanation:

The @my_decorator syntax tells Python to modify say_hello with the extra behavior from my_decorator. Inside the decorator, the wrapper function adds the new behavior (prints "Start" and "End") before and after calling the original say_hello.

In short, decorators allow you to add extra functionality around your function without modifying its core behavior.

© 2024 Nikhil

Comments

Popular posts from this blog

Useful Git Commands for Windows

BackEnd for WebDev

MIddlewares in Express