Subjects

All subjects Django Java Python React Spring Boot JavaScript PHP
Sign Up Free
Interview question

What is a decorator in Python and how does it work? Python में decorator क्या है और यह कैसे काम करता है?

Answer

A decorator is a function that takes another function as input and returns a modified version of it, allowing you to add behavior without changing the original function's code.

def my_decorator(func):
    def wrapper(*args, **kwargs):
        print('Before the function runs')
        result = func(*args, **kwargs)
        print('After the function runs')
        return result
    return wrapper

@my_decorator
def greet(name):
    print(f'Hello, {name}')
    return name

greet('John')
# Before the function runs
# Hello, John
# After the function runs

# The @ syntax is just shorthand for:
def greet2(name):
    print(f'Hello, {name}')
greet2 = my_decorator(greet2)  # exactly what @my_decorator does

# Practical use: timing a function
import time
def timer(func):
    def wrapper(*args, **kwargs):
        start = time.time()
        result = func(*args, **kwargs)
        print(f'{func.__name__} took {time.time() - start:.4f}s')
        return result
    return wrapper

@timer
def slow_function():
    time.sleep(1)

slow_function()  # slow_function took 1.0002s

Decorator एक function है जो दूसरे function को input की तरह लेता है और उसका modified version return करता है, original function का code बदले बिना behavior add करने देता है।

def my_decorator(func):
    def wrapper(*args, **kwargs):
        print('Function चलने से पहले')
        result = func(*args, **kwargs)
        print('Function चलने के बाद')
        return result
    return wrapper

@my_decorator
def greet(name):
    print(f'Hello, {name}')
    return name

greet('John')

# @ syntax का मतलब है:
def greet2(name):
    print(f'Hello, {name}')
greet2 = my_decorator(greet2)

# Practical use - timing
import time
def timer(func):
    def wrapper(*args, **kwargs):
        start = time.time()
        result = func(*args, **kwargs)
        print(f'{func.__name__} took {time.time() - start:.4f}s')
        return result
    return wrapper

@timer
def slow_function():
    time.sleep(1)

Was this answer clear?