วันอาทิตย์ที่ 18 กุมภาพันธ์ พ.ศ. 2567

What are Python decorators and how do they contribute to code modularity and reusability? Provide an example to illustrate their usage.

 Q12: What are Python decorators and how do they contribute to code modularity and reusability? Provide an example to illustrate their usage.

A12:

  • Python Decorators:

    • Decorators in Python are functions that are used to modify or extend the behavior of other functions or methods. They provide a way to wrap a function with additional functionality, enhancing code modularity and reusability.
  • Code Modularity and Reusability:

    • Decorators allow developers to separate concerns and apply reusable behavior to multiple functions without modifying their code directly. This promotes cleaner code, as common functionality can be abstracted into decorators.
# Example of a simple decorator
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!")

# Calling the decorated function
say_hello()

  • In this example, the my_decorator function is a decorator that adds behavior before and after the say_hello function is called. The @my_decorator syntax is a convenient way to apply the decorator to the say_hello function.

Q13: Explain the concept of generators in Python, and provide an example of how they can be used to efficiently handle large datasets.

ไม่มีความคิดเห็น:

แสดงความคิดเห็น

How does the Python Global Interpreter Lock (GIL) impact the performance of multi-threaded programs, and what strategies can be employed to mitigate its effects?

  Q10: How does the Python Global Interpreter Lock (GIL) impact the performance of multi-threaded programs, and what strategies can be emplo...