Python Decorators
Decorators in Python are functions that modify the behavior of other functions without changing their source code. They wrap the original function, adding functionality before and after its execution.
def logging_decorator(func):
def execute_with_logs():
print("Executing function...")
func()
print("Function execution completed.")
return execute_with_logs
@logging_decorator
def display_message():
print("Welcome to Python!")
display_message()
List Comprehensions
List comprehensions provide a concise way to create lists by applying expressions to each item in an iterable.
# Create a list of cubes from 1 to 5
cubes = [num**3 for num in range(1, 6)]
print(cubes)
Generators
Generators produce values on-the-fly using the yield keyword, preserving state between calls.
def number_sequence():
value = 10
print('Starting generator')
yield value
value += 5
print('Continuing execution')
yield value
seq = number_sequence()
print(next(seq))
print(next(seq))
Exception Handling
Python uses try-except blocks to handle errors gracefully during program execution.
try:
result = 10 / 0
except ArithmeticError:
print("Mathematical operation failed")
finally:
print("Cleanup completed")
Closures
Closures are nested functions that remember values from their enclosing scope even after the outer function has finished executing.
def multiplier_factory(factor):
def multiply(value):
return factor * value
return multiply
double = multiplier_factory(2)
print(double(8))
Mutable vs Immutable Types
Mutable objects (lists, dictionaries, sets) can be modified after creation, while immutable objects (integers, strings, tuples) cannot be changed.
Map Function
The map() function applies a given function to each item of an iterable and returns a map object.
values = [2, 4, 6, 8]
doubled = map(lambda x: x * 2, values)
print(list(doubled))
Variable Scope
Local variables are defined within functions and accessible only inside them, while global variables are defined at the module level and acessible throughout the program.
Class Inheritence
Inheritance allows a class to derive properties and methods from a parent class.
class Vehicle:
def __init__(self, model):
self.model = model
def describe(self):
return f"Vehicle model: {self.model}"
class Car(Vehicle):
def describe(self):
return f"Car model: {self.model}"
my_car = Car("Sedan")
print(my_car.describe())
File Operations
Python provides built-in functions for reading from and writing to files using context managers.
with open('document.txt', 'r') as f:
content = f.read()
print(content)