96. Class Decorators

Here are 10 Python snippets demonstrating how to use class decorators to modify or extend class behavior:


1. Basic Class Decorator

def add_method(cls):
    cls.new_method = lambda self: "New Method Added"
    return cls

@add_method
class MyClass:
    def existing_method(self):
        return "Existing Method"

obj = MyClass()
print(obj.existing_method())  # Output: Existing Method
print(obj.new_method())       # Output: New Method Added

2. Logging Class Instantiation

def log_instantiation(cls):
    original_init = cls.__init__

    def new_init(self, *args, **kwargs):
        print(f"Creating an instance of {cls.__name__}")
        original_init(self, *args, **kwargs)

    cls.__init__ = new_init
    return cls

@log_instantiation
class MyClass:
    def __init__(self, name):
        self.name = name

obj = MyClass("Test")  # Output: Creating an instance of MyClass

3. Singleton Pattern with Class Decorator


4. Adding Class Attributes


5. Validating Attribute Values


6. Counting Instances of a Class


7. Enforcing Method Call Logging


8. Extending Class with a Mixin


9. Restricting Attribute Creation


10. Timing Class Method Execution


These examples show how to use class decorators to modify or extend class behavior, from adding attributes or methods to enforcing constraints or improving functionality.

Last updated