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

Writing Parameterized Decorators

Veeg om het menu te tonen

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?

Selecteer het correcte antwoord

question mark

Why might you want to pass arguments to a decorator?

Selecteer het correcte antwoord

Was alles duidelijk?

Hoe kunnen we het verbeteren?

Bedankt voor je feedback!

Sectie 4. Hoofdstuk 3

Vraag AI

expand

Vraag AI

ChatGPT

Vraag wat u wilt of probeer een van de voorgestelde vragen om onze chat te starten.

Sectie 4. Hoofdstuk 3
some-alt