Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
call() decorator in Python
Next article icon

Class as Decorator in Python

Last Updated : 29 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

While function-based decorators are widely used, class-based decorators can offer more flexibility and better organization, especially when the decorator needs to maintain state or requires multiple methods to function properly. A Python class decorator is simply a class that implements the __call__ method, allowing an instance of the class to be used as a decorator.

This article explores the concept of using classes as decorators in Python, illustrating their purpose, implementation, and benefits through practical examples.

Implementing Class Decorators

Example: Let’s consider a simple example where we use a class decorator to log the execution time of a function:

Python
import time  class TimerDecorator:     def __init__(self, func):         self.func = func      def __call__(self, *args, **kwargs):         start_time = time.time()         result = self.func(*args, **kwargs)         end_time = time.time()         print(f"Function {self.func.__name__} executed in {end_time - start_time} seconds")         return result  @TimerDecorator def example_function(n):     total = 0     for i in range(n):         total += i     return total  # Usage print(example_function(1000000)) 

Output
Function example_function executed in 0.06820821762084961 seconds 499999500000 

Class Decorator with *args and **kwargs

In this example, the class decorator demonstrates how you can modify the return value of a function, adding additional logic to its execution.

Example:

  1. LoggerDecorator Class:
    • The __init__ method takes the function to be decorated and stores it.
    • The __call__ method logs the arguments and keyword arguments, calls the original function with these arguments, and returns the result.
  2. greet Function:
    • This is a simple function that takes a name and an optional greeting message.
  3. Using the Decorator:
    • When greet is called, the LoggerDecorator logs the arguments before executing the function.
Python
class LoggerDecorator:     def __init__(self, func):         self.func = func      def __call__(self, *args, **kwargs):         print(f"Arguments: {args}, Keyword Arguments: {kwargs}")         result = self.func(*args, **kwargs)         return result  @LoggerDecorator def greet(name, greeting="Hello"):     return f"{greeting}, {name}!"  # Usage print(greet("Alice")) print(greet("Bob", greeting="Hi")) 

Output
Arguments: ('Alice',), Keyword Arguments: {} Hello, Alice! Arguments: ('Bob',), Keyword Arguments: {'greeting': 'Hi'} Hi, Bob! 

Class Decorator with return Statement

In this example, the class decorator demonstrates how you can modify the return value of a function, adding additional logic to its execution.

Example:

  1. DoubleReturnDecorator Class:
    • The __init__ method takes the function to be decorated and stores it.
    • The __call__ method calls the original function with the provided arguments, then doubles the result and returns it.
  2. add Function:
    • This is a simple function that adds two numbers.
  3. Using the Decorator:
    • When add is called, the DoubleReturnDecorator modifies the return value by doubling it before returning it.
Python
class DoubleReturnDecorator:     def __init__(self, func):         self.func = func      def __call__(self, *args, **kwargs):         result = self.func(*args, **kwargs)         return result * 2  @DoubleReturnDecorator def add(a, b):     return a + b  # Usage print(add(3, 5))   print(add(10, 20))  

Output
16 60 

Checking for an Invalid Parameter with a Class Decorator

In this example, the class decorator demonstrates how you can check for specific parameter values and handle errors appropriately by raising exceptions when conditions are not met.

Example

  1. ErrorCheckDecorator Class:
    • The __init__ method takes the function to be decorated and stores it.
    • The __call__ method checks if the error keyword argument is set to True. If it is, it raises a ValueError. Otherwise, it calls the original function with the provided arguments.
  2. process_data Function:
    • This is a simple function that takes some data and an optional error flag.
  3. Using the Decorator:
    • When process_data is called with error=True, the decorator raises a ValueError. Otherwise, it processes the data normally.
Python
class ErrorCheckDecorator:     def __init__(self, func):         self.func = func      def __call__(self, *args, **kwargs):         if kwargs.get('error', False):             raise ValueError("Invalid parameter 'error' set to True")         return self.func(*args, **kwargs)  @ErrorCheckDecorator def process_data(data, error=False):     return f"Processing data: {data}"  # Usage try:     print(process_data("sample_data"))     print(process_data("sample_data", error=True))  # This will raise ValueError except ValueError as e:     print(e) 

Output
Processing data: sample_data Invalid parameter 'error' set to True 


Next Article
call() decorator in Python

R

RishabhBhatnagar
Improve
Article Tags :
  • Python
  • Python Oops-programs
Practice Tags :
  • python

Similar Reads

  • call() decorator in Python
    Python Decorators are important features of the language that allow a programmer to modify the behavior of a class. These features are added functionally to the existing code. This is a type of metaprogramming when the program is modified at compile time. The decorators can be used to inject modifie
    3 min read
  • Closures And Decorators In Python
    Closures and decorators are powerful features in Python that allow for more advanced and flexible code patterns. Understanding these concepts can greatly enhance your ability to write clean, efficient, and reusable code. Why Python decorators rather than closures?Python decorators are preferred over
    3 min read
  • Decorators in Python
    In Python, decorators are a powerful and flexible way to modify or extend the behavior of functions or methods, without changing their actual code. A decorator is essentially a function that takes another function as an argument and returns a new function with enhanced functionality. Decorators are
    10 min read
  • Conditional Decorators in Python
    In Python, decorators are functions or classes that wrap around a function as a wrapper by taking a function as input and returning out a callable. They allow the creation of reusable building code blocks that can either change or extend behavior of other functions. Conditional Decorators Given a co
    2 min read
  • classmethod() in Python
    The classmethod() is an inbuilt function in Python, which returns a class method for a given function. This means that classmethod() is a built-in Python function that transforms a regular method into a class method. When a method is defined using the @classmethod decorator (which internally calls c
    8 min read
  • delattr() and del() in Python
    In this article, we are going to see delattr() and del() functions in Python delattr() in Python The delattr() method is used to delete the named attribute from the object, with the prior permission of the object. Syntax: delattr(object, name): The function takes only two parameter: object: from whi
    3 min read
  • Descriptor in Python
    In Python, a descriptor is any object that implements at least one of the following methods: __get__(self, instance, owner), __set__(self, instance, value), or __delete__(self, instance). When a class defines any of these methods, its instances become descriptors. Descriptors act as intermediaries i
    5 min read
  • Print Objects of a Class in Python
    In object-oriented programming (OOP), an object is an instance of a class. A class serves as a blueprint, defining the structure and behavior of objects, while an instance is a specific copy of the class with actual values. When an object is created, the class is said to be instantiated. All instanc
    4 min read
  • Chain Multiple Decorators in Python
    In this article, we will try to understand the basic concept behind how to make function decorators and chain them together we will also try to see Python decorator examples.  What is Decorator In Python?A decorator is a function that can take a function as an argument and extend its functionality a
    2 min read
  • Abstract Classes in Python
    In Python, an abstract class is a class that cannot be instantiated on its own and is designed to be a blueprint for other classes. Abstract classes allow us to define methods that must be implemented by subclasses, ensuring a consistent interface while still allowing the subclasses to provide speci
    6 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences