Sobes.tech
Junior — Middle

Can the decorator pattern be applied to classes in Python, and how to implement it?

sobes.tech AI

Answer from AI

Yes, in Python, the decorator pattern can be applied to classes. A class decorator is a class that takes another class or object and extends or modifies its behavior without changing the original code.

Example of implementing a class decorator:

class Decorator:
    def __init__(self, wrapped):
        self._wrapped = wrapped

    def __getattr__(self, name):
        # Delegate attribute calls to the wrapped object
        return getattr(self._wrapped, name)

    def new_method(self):
        return "Additional behavior"


class Original:
    def original_method(self):
        return "Original behavior"


obj = Original()
decorated_obj = Decorator(obj)

print(decorated_obj.original_method())  # Original behavior
print(decorated_obj.new_method())       # Additional behavior

Thus, the class decorator wraps an object and can add new methods or modify existing ones, while preserving the interface of the original object.

Can the decorator pattern be applied to classes in… - sobes.tech