Class decorator is a function that takes a class and returns a modified class.
1import functools23# Class decorator with function4def add_repr(cls):5 @functools.wraps(cls)6 def wrapper(*args, **kwargs):7 return cls(*args, **kwargs)89 def __repr__(self):10 attrs = ", ".join(f"{k}={v!r}" for k, v in self.__dict__.items())11 return f"{cls.__name__}({attrs})"1213 wrapper.__repr__ = __repr__14 return wrapper1516@add_repr17class Point:18 def __init__(self, x, y):19 self.x = x20 self.y = y2122p = Point(1, 2)23print(p) # Point(x=1, y=2)2425# Class decorator with class26debug_all(cls):27 for name, method in vars(cls).items():28 if callable(method):29 def debug_method(m):30 def wrapper(self, *args, **kwargs):31 print(f"Calling {m.__name__}")32 return m(self, *args, **kwargs)33 return wrapper34 setattr(cls, name, debug_method(method))35 return cls
Use cases: