96. Class Decorators

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


1. Basic Class Decorator

Copy

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

Copy

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

Copy


4. Adding Class Attributes

Copy


5. Validating Attribute Values

Copy


6. Counting Instances of a Class

Copy


7. Enforcing Method Call Logging

Copy


8. Extending Class with a Mixin

Copy


9. Restricting Attribute Creation

Copy


10. Timing Class Method Execution

Copy


Last updated