8. 生成器函數
生成器函數允許你定義一個可以“記住”其當前執行狀態的函數,并在下次調用時從上次離開的位置繼續執行。生成器函數使用yield
關鍵字而不是return
。
def simple_generator(): yield 1 yield 2 yield 3 gen = simple_generator()
print(next(gen)) # 輸出:1
print(next(gen)) # 輸出:2
print(next(gen)) # 輸出:3
9. 遞歸函數
遞歸函數是一種直接或間接調用自身的函數。遞歸常用于解決可以分解為更小、相似子問題的任務。
def factorial(n): if n == 0 or n == 1: return 1 else: return n * factorial(n-1) print(factorial(5)) # 輸出:120
10. 上下文管理器(Context Managers)和with
語句
上下文管理器是一個實現了__enter__
和__exit__
方法的對象,用于在with
語句塊中設置和清理資源。
class FileHandler:def __init__(self, filename):self.file = open(filename, 'w')def __enter__(self):return self.filedef __exit__(self, exc_type, exc_val, exc_tb):self.file.close()with FileHandler('output.txt') as f:f.write('Hello, world!')# 文件會在with塊結束時自動關閉
11. 函數作為參數傳遞
函數可以作為參數傳遞給其他函數,也可以從其他函數返回。
def greet(func, name):print(f"Starting greeting...")func(name)print(f"Greeting finished!")def say_hello(name):print(f"Hello, {name}!")greet(say_hello, 'Alice')# 輸出:# Starting greeting...# Hello, Alice!# Greeting finished!
12. 函數式編程:map, filter, reduce
Python 提供了?map()
,?filter()
, 和?reduce()
?等內置函數,它們允許你以函數式編程風格處理數據。
from functools import reduce# 使用map函數squared = map(lambda x: x**2, [1, 2, 3, 4])print(list(squared)) # 輸出:[1, 4, 9, 16]# 使用filter函數even_numbers = filter(lambda x: x % 2 == 0, [1, 2, 3, 4])print(list(even_numbers)) # 輸出:[2, 4]# 使用reduce函數result = reduce(lambda x, y: x + y, [1, 2, 3, 4])print(result) # 輸出:10
13. Lambda 函數(匿名函數)
Lambda 函數是一個簡單的單行函數,可以用在任何需要函數作為參數的地方。
add = lambda x, y: x + y
print(add(3, 4)) # 輸出:7
14. 函數屬性
Python 函數也是對象,可以給它們添加屬性。
def my_function(): pass my_function.version = "1.0"
print(my_function.version) # 輸出:1.0
這些例子涵蓋了 Python 自定義函數的一些高級用法,它們可以幫助你更靈活地編寫和維護代碼。