Sobes.tech
Middle

Is it possible to use decorators for classes?

sobes.tech AI

Answer from AI

Yes, it is possible. Class decorators work similarly to function decorators but are applied to classes. They receive the class as the sole argument and should return the class itself (possibly modified) or a new object that replaces the original class.

# Example of a class decorator
def my_class_decorator(cls):
    print(f"Decorating class: {cls.__name__}")
    # Add a new attribute to the class
    setattr(cls, 'extra_attribute', 'value')
    return cls

# Applying the decorator to a class
@my_class_decorator
class MyClass:
    def __init__(self, x):
        self.x = x

    def display(self):
        print(f"x: {self.x}")

# Using the decorated class
obj = MyClass(10)
obj.display()
print(f"New attribute: {obj.extra_attribute}")

Class decorators are useful for:

  • Adding methods or attributes to a class at the time of definition.
  • Registering classes in registries or stores.
  • Changing the behavior of a class (for example, by replacing it with another class or object).
  • Performing checks or transformations on the class.
  • Implementing patterns such as singleton, factory, and others.