Decorators vs Decorator design Pattern in Python

 The Decorator Pattern and Python decorators are related concepts, but they are not exactly the same thing. Let's clarify the distinction:




Python Decorators:

  • In Python, decorators are a syntactic construct used to modify or extend the behavior of functions or methods. They are applied using the "@" symbol followed by the decorator function.
  • Python decorators are a concise way to apply higher-order functions to functions or methods.

def my_decorator(func): def wrapper(): print("Something is happening before the function is called.") func() print("Something is happening after the function is called.") return wrapper @my_decorator def say_hello(): print("Hello!") say_hello()


Decorator Pattern:

  • The Decorator Pattern is a design pattern used in object-oriented programming. It involves attaching additional responsibilities to an object dynamically by providing a flexible alternative to subclassing for extending functionality.
  • In the Decorator Pattern, you have a base component (e.g., an interface or abstract class), concrete components that implement the base, and decorators that wrap around these components to add or override behavior.



class Component: def operation(self): pass class ConcreteComponent(Component): def operation(self): return "ConcreteComponent" class Decorator(Component): def __init__(self, component): self._component = component def operation(self): return self._component.operation() class ConcreteDecoratorA(Decorator): def operation(self): return f"ConcreteDecoratorA({self._component.operation()})"

Post a Comment

Previous Post Next Post