第八章: 函数知识总结 8.1 内置函数 数学和数值计算 1 2 3 4 5 6 7 8 abs (-2 ) divmod (20 , 3 ) round (4.51 ) pow (10 , 2 ) pow (10 , 2 , 3 ) sum ([1 , 2 , 3 ]) min (5 , 3 , 9 ) max (7 , 3 , 15 )
进制转换 1 2 3 bin (10 ) oct (10 ) hex (10 )
字符编码 1 2 3 4 bytes ("你好" , encoding="utf-8" ) bytearray ("hi" , encoding='utf-8' ) ord ('a' ) chr (65 )
反射函数 1 2 3 4 5 dir (obj) hasattr (obj, 'attr' ) getattr (obj, 'attr' ) setattr (obj, 'attr' , value) delattr (obj, 'attr' )
其他常用内置函数 1 2 3 4 5 len ("hello" ) isinstance (obj, type ) issubclass (cls1, cls2) id (obj) type (obj)
8.2 函数定义与调用 1 2 3 4 5 6 7 8 def function_name (parameters ): """文档字符串:描述函数功能""" return value result = function_name(arguments)
8.3 函数参数 位置参数 1 2 3 4 def test (x, y, z ): print (x, y, z) test(1 , 2 , 3 )
关键字参数 1 2 3 4 def test (x, y, z ): print (x, y, z) test(y=1 , x=2 , z=3 )
默认参数 1 2 3 4 5 def test (x, y, z=2 ): print (x, y, z) test(1 , 2 ) test(1 , 2 , 3 )
可变参数 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 def test (x, *args ): print (x) print (args) test(1 , 2 , 3 , 4 ) def test (x, **kwargs ): print (x) print (kwargs) test(x=1 , y=2 , z=3 ) def test (x, *args, **kwargs ): print (x, args, kwargs) test(1 , 2 , 3 , y=4 , z=5 )
8.4 作用域与命名空间 名称空间 Python 有三层名称空间:
内置名称空间 :Python 解释器启动时创建,包含内置函数全局名称空间 :模块级别创建,包含模块中定义的变量局部名称空间 :函数调用时创建,包含函数内部变量LEGB 规则 变量查找顺序:
Local :局部作用域Enclosing :外部嵌套函数作用域Global :全局作用域Built-in :内置作用域作用域修饰 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 x = 10 def modify_global (): global x x = 20 modify_global() print (x) def outer (): x = 10 def inner (): nonlocal x x = 20 inner() print (x) outer()
8.5 高阶函数特性 函数作为参数传递 1 2 3 4 5 6 7 def apply_function (func, value ): return func(value) def square (x ): return x ** 2 result = apply_function(square, 5 )
函数作为返回值 1 2 3 4 5 6 7 8 9 10 def get_multiplier (factor ): def multiplier (x ): return x * factor return multiplier double = get_multiplier(2 ) triple = get_multiplier(3 ) print (double(5 )) print (triple(5 ))
函数存储在数据结构中 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 def check_balance (): print ("查询账户余额" ) def transfer_money (): print ("转账服务" ) def deposit (): print ("存款服务" ) def withdraw (): print ("取款服务" ) def update_info (): print ("更新个人信息" ) function_list = [check_balance, transfer_money, deposit, withdraw, update_info] function_dict = { 'balance' : check_balance, 'transfer' : transfer_money, 'deposit' : deposit, 'withdraw' : withdraw, 'update' : update_info } def bank_system (): print ("\n欢迎使用银行服务系统" ) print ("您可以通过数字或命令使用服务" ) while True : print ("\n=== 银行服务菜单 ===" ) print ("1. 查询账户余额" ) print ("2. 转账服务" ) print ("3. 存款服务" ) print ("4. 取款服务" ) print ("5. 更新个人信息" ) print ("0. 退出系统" ) print ("\n或者输入命令:balance, transfer, deposit, withdraw, update, exit" ) choice = input ("\n请输入您的选择(数字或命令): " ) if choice == "0" or choice.lower() == "exit" : print ("感谢使用银行服务系统,再见!" ) break if choice.isdigit(): index = int (choice) - 1 if 0 <= index < len (function_list): function_list[index]() else : print ("无效的数字选择,请重新输入" ) elif choice.lower() in function_dict: function_dict[choice.lower()]() else : print ("无效的命令,请重新输入" ) if __name__ == "__main__" : bank_system()
高阶函数设计模式 高阶函数是函数式编程的核心概念,它们接受其他函数作为参数或返回函数作为结果。
函数组合模式 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 def compose (*functions ): """将多个函数组合成一个函数 compose(f, g, h)(x) 等价于 f(g(h(x))) """ def inner (x ): result = x for f in reversed (functions): result = f(result) return result return inner def remove_punctuation (text ): import string return text.translate(str .maketrans('' , '' , string.punctuation)) def lowercase (text ): return text.lower() def remove_whitespace (text ): return ' ' .join(text.split()) process_text = compose(remove_whitespace, lowercase, remove_punctuation) text = "Hello, World! This is an Example." print (process_text(text))
部分应用 部分应用是预先指定一个函数的部分参数,创建一个新的函数。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 from functools import partialdef power (base, exponent ): return base ** exponent square = partial(power, exponent=2 ) print (square(4 )) cube = partial(power, exponent=3 ) print (cube(3 )) powers_of_two = partial(power, 2 ) print (powers_of_two(8 ))
8.6 匿名函数(lambda) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 lambda 参数: 表达式add = lambda x, y: x + y print (add(5 , 3 )) numbers = [1 , 2 , 3 , 4 , 5 ] squares = map (lambda x: x**2 , numbers) print (list (squares)) words = ['apple' , 'banana' , 'cherry' ] sorted_words = sorted (words, key=lambda x: len (x))
8.7 闭包函数 闭包是指内部函数引用了外部函数的变量,并且外部函数返回了内部函数。
1 2 3 4 5 6 7 8 9 10 11 12 def counter (): count = 0 def increment (): nonlocal count count += 1 return count return increment my_counter = counter() print (my_counter()) print (my_counter()) print (my_counter())
8.8 递归函数 递归是一种函数在执行过程中调用自身的编程技巧。
1 2 3 4 5 6 7 8 9 10 def factorial (n ): if n == 0 or n == 1 : return 1 else : return n * factorial(n-1 ) print (factorial(5 ))
递归的关键要素 基本情况(终止条件) :必须定义何时停止递归递归关系 :将问题分解为更小的子问题递归深度限制 1 2 3 import sysprint (sys.getrecursionlimit()) sys.setrecursionlimit(3000 )
递归案例:列表扁平化 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 def flatten_list (nested_list ): """递归扁平化嵌套列表""" result = [] for item in nested_list: if isinstance (item, list ): result.extend(flatten_list(item)) else : result.append(item) return result nested = [1 , [2 , 3 ], [4 , [5 , 6 ], 7 ], 8 , [9 , [10 , [11 , 12 ]]]] print (flatten_list(nested))
8.9 装饰器 装饰器是一种特殊的函数,用于修改其他函数的功能。
基本装饰器 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 import timedef count_time (func ): def wrapper (*args,**kwargs ): start_time = time.time() result = func(*args,**kwargs) end_time = time.time() print ("总共耗时:" ,end_time-start_time) return result return wrapper @count_time def test (): sum = 0 for i in range (10000000 ): sum += i return sum result = test() print (result)
带参数的装饰器 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 import timedef repeat (times ): def count_time (func ): def wrapper (*args, **kwargs ): start_time = time.time() result = None for i in range (times): result = func(*args, **kwargs) print (f"第{i+1 } 次执行完成" ) end_time = time.time() print ("总共耗时:" , end_time - start_time) return result return wrapper return count_time @repeat(3 ) def count_sum (): sum = 0 for i in range (10000000 ): sum += i return sum result = count_sum() print (result)
保留原函数元数据 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 from functools import wrapsdef decorator (func ): @wraps(func ) def wrapper (*args, **kwargs ): """包装函数""" print ("函数执行前" ) result = func(*args, **kwargs) print ("函数执行后" ) return result return wrapper @decorator def say_hello (name ): """打招呼函数""" print (f"Hello, {name} !" ) print (say_hello.__name__) print (say_hello.__doc__)
装饰器叠加 1 2 3 4 5 6 7 8 @decorator1 @decorator2 @decorator3 def function (): pass function = decorator1(decorator2(decorator3(function)))
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 def decorator1 (func ): def wrapper (*args, **kwargs ): print ("装饰器1开始" ) result = func(*args, **kwargs) print ("装饰器1结束" ) return result return wrapper def decorator2 (func ): def wrapper (*args, **kwargs ): print ("装饰器2开始" ) result = func(*args, **kwargs) print ("装饰器2结束" ) return result return wrapper @decorator1 @decorator2 def greet (): print ("问候函数执行" ) greet()
装饰器工厂 创建能够接受多种配置的通用装饰器。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 import functoolsimport timedef retry (exceptions, tries=4 , delay=3 , backoff=2 , logger=None ): """可配置的重试装饰器 Args: exceptions: 要捕获的异常类或异常类元组 tries: 最大尝试次数 delay: 初始延迟时间(秒) backoff: 重试间隔的增长因子 logger: 用于记录警告的日志对象 """ def decorator (func ): @functools.wraps(func ) def wrapper (*args, **kwargs ): mtries, mdelay = tries, delay last_exception = None while mtries > 0 : try : return func(*args, **kwargs) except exceptions as e: last_exception = e msg = f"{func.__name__} : 重试 {tries - mtries + 1 } /{tries} 失败: {e} " if logger: logger.warning(msg) else : print (msg) time.sleep(mdelay) mdelay *= backoff mtries -= 1 raise last_exception return wrapper return decorator import requests@retry(exceptions=(requests.RequestException, ConnectionError ), tries=3 , delay=1 , backoff=2 )def fetch_url (url ): """获取URL内容,失败时自动重试""" response = requests.get(url, timeout=2 ) response.raise_for_status() return response.text try : content = fetch_url("https://this-website-does-not-exist-123456789.com" ) print (content) except requests.RequestException as e: print (f"获取内容失败: {e} " )