Student Activity

Student Activity Guide:

1) Understanding and Implementing Decorators

  • Create a simple decorator that logs function execution.

  • Implement a decorator to measure execution time of a function.

Example Code:

def log_decorator(func):
    def wrapper(*args, **kwargs):
        print(f"Executing {func.__name__}...")
        return func(*args, **kwargs)
    return wrapper

@log_decorator
def greet(name):
    print(f"Hello, {name}!")

greet("Alice")

Student Exercise: Implement a decorator that counts the number of times a function is called.

2) Understanding and Implementing Generators

  • Create a generator function to yield even numbers up to a limit.

  • Use a generator to read a large file line by line.

Example Code:

Student Exercise: Implement a Fibonacci sequence generator.

3) Understanding and Implementing Descriptors

  • Create a descriptor to validate attribute values.

  • Implement a descriptor to enforce read-only attributes.

Example Code:

Student Exercise: Implement a descriptor that ensures an attribute is always a string.

4) Using @property, @staticmethod, and @classmethod

  • Demonstrate the use of @property for read-only attributes.

  • Implement @staticmethod and @classmethod to modify class behavior.

Example Code:

Student Exercise: Implement a class with @property for read-only attributes and @classmethod to modify class-level attributes.

5) Performance Benefits of Generators

  • Compare memory usage of lists and generators.

  • Implement a generator that filters large dataset values efficiently.

Example Code:

Student Exercise: Compare execution time of list comprehensions vs generators for large datasets.

Last updated