DEV Community

niuniu
niuniu

Posted on

Quick Tip: Python Decorators Explained

Quick Tip

Python decorators explained:

# Simple decorator
def my_decorator(func):
    def wrapper():
        print("Before function call")
        func()
        print("After function call")
    return wrapper

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

# Decorator with arguments
def repeat(times):
    def decorator(func):
        def wrapper(*args, **kwargs):
            for _ in range(times):
                result = func(*args, **kwargs)
            return result
        return wrapper
    return decorator

@repeat(times=3)
def greet(name):
    print(f"Hello, {name}!")
Enter fullscreen mode Exit fullscreen mode

Powered by MonkeyCode: https://monkeycode-ai.net/

python #coding #tips

Top comments (0)