Decorators

Durum
Üzgünüz bu konu cevaplar için kapatılmıştır...
The sea does not like to be restrained.
Emektar Üye
Katılım
15 Tem 2021
Mesajlar
1,724
Çözümler
86
Tepki puanı
665
Ödüller
10
Yaş
25
Sosyal
4 HİZMET YILI
A decorator is a special type of function that can modify or enhance the behavior of another function. Decorators allow you to add functionality to a function without changing its implementation. They are widely used in Python to add features such as caching, logging, authentication, and more to existing functions.

In Python, a decorator is defined using the @ symbol followed by the name of the decorator function. The decorator function takes a function as an argument, and returns a new function that wraps the original function with some additional functionality. Here's an example:

Python:
def my_decorator(func):
    def wrapper():
        print("Before function execution")
        func()
        print("After function execution")
    return wrapper

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

say_hello()

In this example, we define a decorator function my_decorator, which takes a function as an argument and returns a new function wrapper that adds some print statements before and after the original function is executed. We then use the decorator syntax (@my_decorator) to apply the decorator to the say_hello function.

When we call say_hello(), it is actually the wrapper function returned by the my_decorator function that gets executed. This function first prints "Before function execution", then calls the original say_hello function, and finally prints "After function execution". The output of the program is:

Python:
Before function execution
Hello, world!
After function execution

Decorators can also take arguments, allowing you to customize their behavior. For example, you can define a decorator that caches the results of a function to improve its performance:

Python:
def memoize(func):
    cache = {}
    def wrapper(*args):
        if args in cache:
            return cache[args]
        result = func(*args)
        cache[args] = result
        return result
    return wrapper

@memoize
def fibonacci(n):
    if n in (0, 1):
        return n
    return fibonacci(n-1) + fibonacci(n-2)

print(fibonacci(10))  # Output: 55

In this example, we define a decorator function memoize that creates a cache to store the results of the original function fibonacci. The wrapper function returned by memoize checks if the arguments passed to fibonacci are already in the cache, and returns the cached result if they are. Otherwise, it calls the original fibonacci function to compute the result, caches it, and returns it.

When we call fibonacci(10), the memoize decorator ensures that the function is only computed once for each value of n, and that subsequent calls with the same value of n return the cached result.
 
Onaylı Üye
Katılım
15 Kas 2020
Mesajlar
53
Tepki puanı
5
Ödüller
5
Sosyal
5 HİZMET YILI
Decorators in Python are a powerful feature that allows you to modify the behavior of functions or classes. Here are some additional points about decorators:

  1. Decorator Syntax: Decorators are defined using the @ symbol followed by the name of the decorator function or class. The decorator is placed before the function or class that it modifies. For example:
    Python:
    @decorator
    def my_function():
        # Function body
        pass
  2. Decorating Functions: Decorators are commonly used to modify the behavior of functions. A decorator function takes a function as an argument, wraps it with additional functionality, and returns the wrapped function. Here's an example:
    Python:
    def decorator(func):
        def wrapper():
            # Additional functionality
            func()
            # Additional functionality
        return wrapper
    
    @decorator
    def my_function():
        # Function body
        pass
    In this example, the decorator function decorator wraps the my_function with additional functionality defined in the wrapper function. The @decorator syntax applies the decorator to my_function.

  3. Decorating Classes: Decorators can also be applied to classes. In this case, the decorator function or class modifies the class itself, rather than individual methods. Here's an example:
    Python:
    def decorator(cls):
        # Modify the class
        return cls
    
    @decorator
    class MyClass:
        pass
    In this example, the decorator function decorator modifies the MyClass class.

  4. Multiple Decorators: You can apply multiple decorators to a function or class by stacking them using the @ syntax. The decorators are applied in the order they appear, from top to bottom. For example:
    Python:
    @decorator1
    @decorator2
    def my_function():
        pass
    In this example, my_function is first decorated by decorator2, and then the resulting decorated function is decorated by decorator1.

  5. Decorator with Arguments: Decorators can take arguments by creating a decorator factory function that returns the actual decorator. The decorator factory function takes the arguments and returns the decorator function. Here's an example:
    Python:
    def decorator_factory(arg1, arg2):    
        def decorator(func):
            # Modify the function using arg1 and arg2
            return func
        return decorator
    
    @decorator_factory('arg1_value', 'arg2_value')
    def my_function():
        pass
    In this example, decorator_factory is a function that takes arguments arg1 and arg2 and returns the actual decorator function. The decorator function modifies the function using the provided arguments.
Decorators are a powerful tool in Python that allow you to modify the behavior of functions or classes without changing their implementation. They are widely used in areas such as logging, caching, authentication, and more.
 
Son düzenleme:
Uzman Üye
Katılım
20 Tem 2021
Mesajlar
152
Tepki puanı
4
Ödüller
4
Yaş
31
4 HİZMET YILI
thanks for this topic decorators are power since I know it as I'm a nestJS developer :)
 
Durum
Üzgünüz bu konu cevaplar için kapatılmıştır...
Üst