Class Decorators in Python šŸŽÆ

beginner
11 min

Class Decorators in Python šŸŽÆ

Welcome to our deep dive into Python Decorators, focusing on Class Decorators! Let's explore how to enhance and customize your classes using this powerful feature.

Understanding Class Decorators šŸ“

Class Decorators are special types of functions that modify the behavior of a class before the class is created. They are used to add new functionality to existing classes without modifying their source code.

python
def class_decorator(a_class): def wrapper(*args, **kwargs): # Add new functionality here instance = a_class(*args, **kwargs) return instance return wrapper

šŸ’” Pro Tip: Decorators are denoted by the @ symbol in Python.

Creating a Simple Class Decorator šŸŽÆ

Let's create a simple class decorator that logs the creation of instances for our class.

python
def log_creation(a_class): def wrapper(*args, **kwargs): instance = a_class(*args, **kwargs) print(f"Created an instance of {a_class.__name__}") return instance return wrapper @log_creation class MyClass: pass my_instance = MyClass() # Output: Created an instance of MyClass

Advanced Class Decorator Example šŸŽÆ

In this example, we'll create a decorator that times the execution of methods within a class.

python
import time def timed(func): def wrapper(*args, **kwargs): start_time = time.time() result = func(*args, **kwargs) end_time = time.time() print(f"Method '{func.__name__}' executed in {end_time - start_time} seconds.") return result return wrapper @timed def add(x, y): return x + y result = add(3, 4) # Output: Method 'add' executed in 0.00050239447021484375 seconds. # The result is 7

Quiz šŸŽÆ

Quick Quiz
Question 1 of 1

What is a Class Decorator in Python?

By understanding and mastering Class Decorators, you'll be able to create more modular and reusable code in your Python projects. Happy coding! šŸ’”šŸŽÆ