Chapter 18: Advanced Python Concepts
Loveleen Sharma (philomath)
Tech Expert | Full Stack Developer | AI/ML Trainer | PowerPlatform Developer | Data & Business Analytics Enthusiast | Blockchain Enthusiast | Building Innovative Solutions
Let's dive deeper into advanced Python concepts with practical examples:
Decorators:
Decorators enhance function behavior. Here are detailed examples:
Example 1: Creating a decorator for logging function calls:
def log_function_call(func):
def wrapper(*args, **kwargs):
print(f"Calling {func.__name__} with args: {args}, kwargs: {kwargs}")
result = func(*args, **kwargs)
print(f"{func.__name__} returned: {result}")
return result
return wrapper
@log_function_call
def add(a, b):
return a + b
result = add(3, 5)
Generators
Generators are great for handling large datasets. Here's a detailed example for Fibonacci numbers:
Example 2: Creating a generator for Fibonacci numbers:
def fibonacci():
a, b = 0, 1
while True:
yield a
a, b = b, a + b
fib_gen = fibonacci()
for _ in range(10):
print(next(fib_gen))
Context Managers
Context managers simplify resource management. Example for file handling:
Example 3: Using a context manager for file handling:
class FileManager:
def __init__(self, filename, mode):
self.filename = filename
self.mode = mode
def __enter__(self):
self.file = open(self.filename, self.mode)
return self.file
def __exit__(self, exc_type, exc_value, traceback):
self.file.close()
with FileManager('example.txt', 'w') as file:
file.write('Hello, context managers!')
Explore these advanced Python concepts with detailed code examples and enhance your programming skills. #PythonProgramming #AdvancedTopics #CodingExamples #LoveLogicByte