Decorators

Decorators are a powerful feature in Python that allow you to modify or extend the behavior of a function or method without changing its actual code.

In simple words:
A decorator adds extra functionality to an existing function.

Why Use Decorators?

  • Add extra behavior (like logging, validation, authentication)
  • Avoid code repetition
  • Keep code clean and reusable
  • Follow DRY principle (Don’t Repeat Yourself)

Basic Concept

In Python, functions are first-class objects.
This means:

  • Functions can be stored in variables
  • Functions can be passed as arguments
  • Functions can return other functions

Decorators use this concept.

Basic Example Without @ Syntax

def greet():
print("Hello")def decorator_function(func):
def wrapper():
print("Before function call")
func()
print("After function call")
return wrappergreet = decorator_function(greet)
greet()

Output:

Before function call
Hello
After function call

The decorator added extra behavior before and after the function.

Using @ Decorator Syntax

Python provides a cleaner way using @.

def decorator_function(func):
def wrapper():
print("Before function call")
func()
print("After function call")
return wrapper@decorator_function
def greet():
print("Hello")greet()

This is the same as:

greet = decorator_function(greet)

Decorator with Arguments

If the original function has parameters:

def decorator_function(func):
def wrapper(name):
print("Before function call")
func(name)
print("After function call")
return wrapper@decorator_function
def greet(name):
print("Hello", name)greet("Hira")

**Using *args and kwargs (Best Practice)

To handle any number of arguments:

def decorator_function(func):
def wrapper(*args, **kwargs):
print("Before function call")
result = func(*args, **kwargs)
print("After function call")
return result
return wrapper

This makes the decorator flexible.

Built-in Decorators in Python

@staticmethod
@classmethod
@property

Example:

class Student:
def __init__(self, marks):
self._marks = marks @property
def marks(self):
return self._marks

Now marks can be accessed like a variable, not a method.

Key Points

  • Decorators take a function as input
  • They return a new function
  • Use @ syntax for cleaner code
  • Useful for logging, timing, authentication, validation

Key Takeaway

Decorators allow you to add extra functionality to functions or methods without modifying their original code.

They make programs cleaner, reusable, and more powerful in Python.

Home » OBJECT ORIENTED PROGRAMMING IN PYTHON (OOP) > Advanced OOP > Decorators