Python - Decorators

Why should I learn to solve Python: Decorators technical interview questions?

Learn and practise solving Python: Decorators technical interview questions and answers to enhance your skills for clearing technical interviews, HR interviews, campus interviews, and placement tests.

Where can I get technical Python: Decorators technical interview questions and answers with explanations?

IndiaBIX provides you with lots of fully solved Python: Decorators technical interview questions and answers with a short answer description. You can download Python: Decorators technical interview questions and answers as PDF files or e-books.

How do I answer Python: Decorators technical interview questions from various companies?

You can answer all kinds of Python: Decorators technical interview questions by practising the given exercises (short answer type). You can also find the frequently asked Python: Decorators technical interview questions with answers from various companies, such as TCS, Wipro, Infosys, CTS, IBM, etc.

1.
What is a decorator in Python?

In Python, a decorator is a design pattern that allows you to extend or modify the behavior of callable objects (functions or methods) without modifying their actual code. Decorators are applied using the "@" syntax.

Here is a simple example:

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()

In the above example, my_decorator is a decorator function that takes another function func as its argument and returns a new function wrapper. The wrapper function contains the code that is executed before and after calling the original func. The @my_decorator syntax is a shorthand for say_hello = my_decorator(say_hello).

When you run this program, you will get the following output:

Something is happening before the function is called.
Hello!
Something is happening after the function is called.

2.
Explain the purpose of using decorators in Python.

In Python, decorators provide a way to modify or extend the behavior of functions or methods without changing their actual code. They are a powerful tool for code reusability, readability, and maintaining a clean and modular codebase.

Decorators are often used for tasks such as logging, access control, memoization, and more. They allow you to wrap functions with additional functionality, making the code more concise and promoting the separation of concerns.

Here's an example to illustrate the purpose of decorators:

# Decorator function
def log_function_call(func):
    def wrapper(*args, **kwargs):
        print(f"Calling function {func.__name__} with arguments {args} and keyword arguments {kwargs}")
        result = func(*args, **kwargs)
        print(f"{func.__name__} returned {result}")
        return result
    return wrapper

# Applying the decorator
@log_function_call
def add(a, b):
    return a + b

# Using the decorated function
result = add(3, 5)

In this example, the log_function_call decorator is applied to the add function. It wraps the original function with additional logging statements, printing information about the function call and its result.

When you run this program, you will get the following output:

Calling function add with arguments (3, 5) and keyword arguments {}
add returned 8

3.
How do you define a decorator in Python?

In Python, a decorator is defined as a function that takes another function as its argument and returns a new function that usually extends or modifies the behavior of the original function. Decorators are applied using the "@" syntax.

Here is how you define a decorator:

def my_decorator(func):
    def wrapper(*args, **kwargs):
        # Code to be executed before the original function is called
        result = func(*args, **kwargs)
        # Code to be executed after the original function is called
        return result
    return wrapper

The my_decorator function takes another function func as its argument and returns a new function wrapper. The wrapper function contains the code that is executed before and after calling the original func.

Here's an example of using the decorator:

# Applying the decorator
@my_decorator
def example_function():
    print("Inside the original function")

# Using the decorated function
example_function()

In this example, the @my_decorator syntax is a shorthand for example_function = my_decorator(example_function). The example_function is then replaced by the wrapper function, which contains the additional functionality defined in the decorator.

When you run this program, you will not see any output because the decorator in this example does not add any specific behavior. The purpose here is to illustrate the structure of defining a decorator.


4.
Discuss the syntax of applying a decorator to a function.

In Python, you apply a decorator to a function using the "@" syntax. The decorator is placed above the function definition, and it is a concise way to indicate that the function should be wrapped or modified by the decorator.

Here is the syntax:

@decorator_function
def my_function():
    # Function code

In the above syntax:

  • @decorator_function: This line indicates that the function my_function should be decorated by the decorator_function.
  • def my_function():: This is the definition of the function that will be modified or extended by the decorator.

Here's an example to illustrate the syntax:

# Decorator function
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

# Applying the decorator
@my_decorator
def say_hello():
    print("Hello!")

# Using the decorated function
say_hello()

In this example, @my_decorator is applied above the say_hello function definition. The say_hello function is then replaced by the wrapper function returned by the decorator.

When you run this program, you will get the following output:

Something is happening before the function is called.
Hello!
Something is happening after the function is called.