
本文讲解python中函数间共享数据的两种主流方法:使用global声明访问全局变量,以及更推荐的参数传递与返回值方式,帮助你避免“变量未定义”错误并写出可维护的代码。
本文讲解python中函数间共享数据的两种主流方法:使用global声明访问全局变量,以及更推荐的参数传递与返回值方式,帮助你避免“变量未定义”错误并写出可维护的代码。
在Python中,函数内部定义的变量默认具有局部作用域,这意味着read()中定义的foot和inch无法被calculate()或write()直接访问——这正是你遇到NameError: name 'foot' is not defined的根本原因。解决该问题有两种清晰路径:全局变量方案(快速但不推荐用于复杂逻辑)和参数-返回值方案(结构清晰、易于测试、符合函数式编程原则)。
✅ 方案一:使用 global 声明(仅作理解,慎用)
需在所有修改全局变量的函数内显式声明global,并在模块顶层预先定义变量:
# 全局变量声明(必须在函数外初始化)
foot = inch = 0
foot_to_meter = foot_to_centimeter = 0
inch_to_meter = inch_to_centimeter = 0
def read():
global foot, inch
foot = int(input("Foot? "))
inch = int(input("Inch? "))
def calculate():
global foot, inch, foot_to_meter, foot_to_centimeter, inch_to_meter, inch_to_centimeter
foot_to_meter = 0.3048 * foot
foot_to_centimeter = 155 * foot_to_meter # ⚠️ 注意:此处155倍换算逻辑存疑,实际应为 ×100
inch_to_meter = (1.5 / 12) * 5.4530 * inch # ⚠️ 此公式非常规(标准为 1 inch = 0.0254 m)
inch_to_centimeter = 155 * inch_to_meter
def write():
print(f"The {foot} foot is {foot_to_meter:.4f} meters")
print(f"The {foot} foot is {foot_to_centimeter:.4f} centimeters")
print(f"The {inch} inch is {inch_to_meter:.4f} meters")
print(f"The {inch} inch is {inch_to_centimeter:.4f} centimeters")
if __name__ == "__main__":
read()
calculate()
write()
⚠️ 注意事项:
- global易导致状态混乱,难以调试,且无法支持多组独立数据计算;
- 示例中的单位换算系数(如155、5.4530)不符合国际标准(1 ft = 0.3048 m,1 in = 2.54 cm),建议核对业务需求或采用标准值。
✅ 方案二:参数传递 + 返回值(推荐!专业实践)
将数据作为输入参数传入,函数通过return输出结果,由调用方负责流转——完全消除全局依赖,提升可读性与可测试性:
def feet_to_meters(feet):
return feet * 0.3048
def feet_to_centimeters(feet):
return feet_to_meters(feet) * 100
def inches_to_meters(inches):
return inches * 0.0254
def inches_to_centimeters(inches):
return inches_to_meters(inches) * 100
def read():
feet = int(input("Feet? "))
inches = int(input("Inches? "))
return feet, inches # 返回元组
def write(feet, inches):
print(f"{feet} feet = {feet_to_meters(feet):.4f} meters")
print(f"{feet} feet = {feet_to_centimeters(feet):.4f} centimeters")
print(f"{inches} inches = {inches_to_meters(inches):.4f} meters")
print(f"{inches} inches = {inches_to_centimeters(inches):.4f} centimeters")
# 主流程:数据单向流动,职责分明
if __name__ == "__main__":
f, i = read() # 获取输入
write(f, i) # 直接使用,无需中间存储
✅ 总结与最佳实践
- 永远优先选择参数传递:它使函数具备确定性(相同输入必得相同输出)、可复用性(如write(5, 12)可离线测试)和可组合性;
- 避免global用于业务逻辑:仅在极少数场景(如配置开关、计数器)中谨慎使用;
- 单位换算请遵循标准:1 英尺 = 0.3048 米,1 英寸 = 2.54 厘米(即 0.0254 米);
- 进阶建议:可进一步封装为类(如LengthConverter),或使用dataclass管理输入/输出结构,提升工程化水平。
通过参数驱动的数据流,你的代码将更健壮、更易协作,也真正践行了“高内聚、低耦合”的软件设计原则。
Python免费学习笔记(深入):立即使用
在学习笔记中,你将探索 Python 的核心概念和高级技巧!











