Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lära Writing Parameterized Decorators | Mastering Python Decorators
Functional Programming Concepts in Python

Writing Parameterized Decorators

Svep för att visa menyn

When you want your decorator to behave differently depending on some input, you need to create a parameterized decorator. Unlike regular decorators, which only take the function as an argument, parameterized decorators accept their own arguments, allowing you to control their behavior dynamically. This is especially useful when you want to reuse a decorator in multiple situations with different configurations.

The Structure of a Parameterized Decorator:

  1. The outer function accepts the decorator arguments;
  2. The middle function is the actual decorator that takes the function to be decorated;
  3. The inner function wraps and controls the execution of the original function.

This layered approach lets you pass arguments to the decorator, which are then available when the decorated function is called.

12345678910111213141516171819202122
# Outer function: accepts the decorator argument 'times' def repeat(times): # The actual decorator that takes the function to be decorated def decorator(func): # Inner function: wraps and controls the execution of 'func' def wrapper(*args, **kwargs): result = None # Call the original function 'times' times for _ in range(times): result = func(*args, **kwargs) return result # Return the wrapper to replace the original function return wrapper # Return the decorator function return decorator # Apply the repeat decorator @repeat(3) def say_hello(): print("Hello!") say_hello()

1. How does a parameterized decorator differ from a regular decorator?

2. Why might you want to pass arguments to a decorator?

question mark

How does a parameterized decorator differ from a regular decorator?

Vänligen välj det korrekta svaret

question mark

Why might you want to pass arguments to a decorator?

Vänligen välj det korrekta svaret

Var allt tydligt?

Hur kan vi förbättra det?

Tack för dina kommentarer!

Avsnitt 4. Kapitel 3

Fråga AI

expand

Fråga AI

ChatGPT

Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal

Avsnitt 4. Kapitel 3
some-alt