Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Syntax | Decorators
Intermediate Python: Arguments, Scopes and Decorators
course content

Conteúdo do Curso

Intermediate Python: Arguments, Scopes and Decorators

Intermediate Python: Arguments, Scopes and Decorators

1. Packing and Unpacking
2. Arguments in Function
3. Function as an Argument
4. Variable Scope
5. Decorators

bookSyntax

Decorator works by taking a function as an argument and then executing it within a wrapper function.

To apply a decorator, one can use the @ symbol followed by the decorator function's name, placed right above the function that needs to be modified. Here's an example:

In this example, both methods achieve the same outcome. The first method, using the @ symbol, is a more readable and concise way to apply decorators, often referred to as "syntactic sugar".

It's typical to use a nested function named wrapper within decorators.

Flexible Decorators: Accommodating Diverse Function Arguments

Functions often require a varying number of arguments. To develop a decorator capable of being applied to functions with differing argument counts, it's effective to utilize *args and **kwargs in the wrapper() function.

1234567891011121314151617181920212223242526272829303132333435
def indicate(func): def wrapper(*args, **kwargs): print("=" * 15) print("Taken arguments:", *args, kwargs) result = func(*args, **kwargs) print("=" * 15) return result return wrapper @indicate def avg_two(a, b): '''Calculate the average of two numbers''' return round((a + b) / 2, 1) @indicate def avg_three(a, b, c): '''Calculate the average of three numbers''' return round((a + b + c) / 3, 1) @indicate def avg_many_kwargs(**kwargs): '''Calculate the average of multiple numbers in a dictionary''' keys = 0 total = 0 for value in kwargs.values(): keys += 1 total += value return round(total / keys, 1) print("Returned:", avg_two(14, 21), "\n") print("Returned:", avg_three(225, 12, 11), "\n") print("Returned:", avg_many_kwargs(first=51, second=11, third=47, fourth=93))
copy

Tudo estava claro?

Como podemos melhorá-lo?

Obrigado pelo seu feedback!

Seção 5. Capítulo 2
some-alt