Junior — Middle
Can you apply decoration to a class in object-oriented programming?
sobes.tech AI
Answer from AI
Yes, in object-oriented programming, decoration can be applied to classes. This is implemented through the "Decorator" pattern — a wrapper around an object that adds new behavior without modifying the original class.
In Python, this is often done using decorator classes that accept an object in the constructor and override the necessary methods, supplementing or changing their behavior.
Example:
class Component:
def operation(self):
return "Basic behavior"
class Decorator:
def __init__(self, component):
self._component = component
def operation(self):
# Additional behavior before call
result = self._component.operation()
# Additional behavior after call
return f"Decorated -> {result}"
# Usage
component = Component()
decorated = Decorator(component)
print(decorated.operation()) # Outputs: Decorated -> Basic behavior
Thus, decoration allows dynamically extending the functionality of objects without changing their code.