Zone Of Makos

Menu icon

Decorator in Python

In Python, a decorator is a function that takes another function as input and extends or modifies the behavior of the original function without changing its source code. Decorators are a powerful tool for adding functionality to functions and classes in a modular way, and they are widely used in Python libraries and frameworks.

Syntax of a Decorator

A decorator is a function that takes another function as input and returns a new function that extends or modifies the behavior of the original function. The syntax of a decorator is as follows:


def my_decorator(func):
    def wrapper():
        print("Before the function is called.")
        func()
        print("After the function is called.")
    return wrapper

@my_decorator
def my_function():
    print("Hello, World!")

my_function()

In this example, the my_decorator function is a decorator that takes a function called func as input and returns a new function called wrapper that adds some extra functionality to the original function. The @my_decorator syntax is shorthand for my_function = my_decorator(my_function) , which applies the my_decorator function to the my_function function.

Class Decorators

In addition to function decorators, Python also supports class decorators, which are similar to function decorators but take a class as input and return a new class that extends or modifies the behavior of the original class.


def my_class_decorator(cls):
    class NewClass:
        def __init__(self, *args, **kwargs):
            self.instance = cls(*args, **kwargs)
        def __getattr__(self, name):
            return getattr(self.instance, name)
        def new_method(self):
            print("New method added to the class.")
    return NewClass

@my_class_decorator
class MyClass:
    def my_method(self):
        print("Original method of the class.")

my_object = MyClass()
my_object.my_method()
my_object.new_method()

In this example, the my_class_decorator function is a class decorator that takes a class called cls as input and returns a new class called NewClass that extends or modifies the behavior of the original class. The @my_class_decorator syntax is shorthand for MyClass = my_class_decorator(MyClass) , which applies the my_class_decorator function to the MyClass class.

Conclusion

Decorators are a powerful tool in Python that allow you to extend or modify the behavior of functions and classes without changing their source code. Function decorators take a function as input and return a new function that adds extra functionality to the original function, while class decorators take a class as input and return a new class that extends or modifies the behavior of the original class.