Home Python C Language C ++ HTML 5 CSS Javascript Java Kotlin SQL DJango Bootstrap React.js R C# PHP ASP.Net Numpy Dart Pandas Digital Marketing

Function Decorators and Class Decorators in Python


In Python, decorators are a way to modify or enhance the behavior of functions or classes. They allow you to "decorate" or "wrap" a function or class with additional functionality. There are two main types of decorators in Python: Function Decorators and Class Decorators.

Function Decorators

A function decorator is a function that takes another function as input and returns a new function that typically extends the behavior of the original function.

Example of Function Decorator:

    def my_decorator(func):
        def wrapper():
            print("Something is happening before the function is called.")
            func()
            print("Something is happening after the function is called.")
        return wrapper

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

    say_hello()
        

In this example, we defined a decorator function called my_decorator. This decorator takes a function (func) as input and returns a new function, wrapper, which extends the behavior of the original function by printing additional messages before and after calling the original function.

Output:

    Something is happening before the function is called.
    Hello!
    Something is happening after the function is called.
        

Class Decorators

Class decorators are used to modify or enhance the behavior of a class. Similar to function decorators, class decorators are functions that take a class as input and return a new class.

Example of Class Decorator:

    def my_class_decorator(cls):
        class WrappedClass(cls):
            def new_method(self):
                print("This is a new method added by the decorator.")
        return WrappedClass

    @my_class_decorator
    class MyClass:
        def original_method(self):
            print("This is the original method.")

    obj = MyClass()
    obj.original_method()
    obj.new_method()
        

In this example, we defined a decorator called my_class_decorator, which takes a class (cls) as input and creates a new class, WrappedClass, which extends the functionality of the original class by adding a new method new_method.

Output:

    This is the original method.
    This is a new method added by the decorator.
        

Conclusion

Decorators in Python provide a clean and elegant way to modify or extend the behavior of functions and classes. Function decorators are used to enhance or modify the behavior of functions, while class decorators are used to modify the behavior of classes. Decorators allow for greater flexibility and reuse of code, making them a powerful tool in Python programming.



Advertisement





Q3 Schools : India


Online Complier

HTML 5

Python

java

C++

C

JavaScript

Website Development

HTML

CSS

JavaScript

Python

SQL

Campus Learning

C

C#

java