在 Python 编程的世界中,掌握高级概念和技术是提升编程能力的关键。本文将带领您深入探索 Python 的高级特性,通过实际的代码示例展示其强大之处。
import time def timeit(func): def wrapper(*args, **kwargs): start_time = time.time() result = func(*args, **kwargs) end_time = time.time() print(f"Function {func.__name__} took {end_time - start_time} seconds to execute.") return result return wrapper @timeit def my_function(): # 这里是函数的具体实现 time.sleep(2) print("Function completed.")
def fibonacci_generator(): a, b = 0, 1 while True: yield a a, b = b, a + b fib_gen = fibonacci_generator() for _ in range(10): print(next(fib_gen))
class FileHandler: 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_val, exc_tb): self.file.close() with FileHandler('example.txt', 'w') as file: file.write("Hello, World!")
import threading import time def task(name): print(f"Starting task {name}") time.sleep(2) print(f"Task {name} completed") threads = [] for i in range(5): thread = threading.Thread(target=task, args=(f"Task {i}",)) threads.append(thread) thread.start() for thread in threads: thread.join()