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.
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.
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.
Let's create a simple class decorator that logs the creation of instances for our class.
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 MyClassIn this example, we'll create a decorator that times the execution of methods within a class.
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 7What 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! š”šÆ