如何在函数间共享列表(非全局变量)?文本游戏参数报错解决
问题解决:无全局变量下共享物品列表
问题分析
原代码存在两个核心错误:
items()函数的参数完全多余,函数内部直接覆盖了传入的参数,且你从未调用该函数初始化items_held变量,导致后续传参时提示变量未定义- 调用
shop()时未传入必需的items_held参数,触发"missing 1 required positional argument"错误
解决方案
利用Python可变对象的引用传递特性(列表属于可变对象),通过函数参数传递列表即可实现多函数共享状态,无需全局变量。修改步骤如下:
- 修正初始化物品列表的函数:移除多余参数,直接返回初始物品集合
- 在主逻辑中先初始化物品列表,再将其作为参数传递给
shop()及其他需要操作物品的函数
修改后的完整代码:
def init_items(): # 直接返回初始物品列表,无需接收参数 return ["Money"] def shop(items_held): print("You look around the shop for items.") print("Here is what you find that's useful for defending your home: ") shop_items = ["Wood", "Tool box", "Bear spray"] user_choice = input("Do you wish to buy these? (y/n) ") if user_choice.lower() == "y" and "Money" in items_held: items_held.extend(shop_items) # 补充购买逻辑:移除Money,符合消费场景 items_held.remove("Money") print("You have bought the items.") print("You go back.") else: print("You don't have the money or chose not to buy.") print(f"Current items: {items_held}") # 主逻辑流程 player_items = init_items() # 将初始化好的列表传入shop函数 shop(player_items) # 后续其他需要操作物品的函数,直接传递player_items即可 # 示例:def defend(items_held): ... 调用时使用 defend(player_items)
关键说明
- 列表是可变对象,函数内部对
items_held的修改(如extend、remove)会直接作用于原列表,因此后续函数传递同一个列表变量就能获取最新状态 - 所有需要操作物品列表的函数,都通过参数接收该列表,既避免了全局变量的副作用,又保持了代码的模块化和可维护性
内容的提问来源于stack exchange,提问作者SancHO
相关产品推荐
相关产品推荐

