Python中创建动态命名变量:植物管理练习程序开发疑问
解决方法:用容器存储植物实例
不要尝试动态生成不重复的变量名,这在Python里既不推荐也没必要,更好的方式是用列表或者字典来统一管理所有植物实例,这样既能避免覆盖问题,还能方便后续对植物进行查询、修改等操作。
具体实现步骤
- 定义一个容器(比如列表
plants = [])来保存所有植物实例 - 修改
CreatePlant函数,让它返回创建好的Plant对象 - 每次调用
CreatePlant后,把返回的对象添加到容器中
修改后的完整代码
class Plant: def __init__(self, name, location, watering_days): self.name = name self.location = location self.watering_days = watering_days def create_plant(): name = input("Okay, what is this plant called?\n") location = input("Where in/around your house is this plant? (Multiple locations are fine.) Located at:\n") watering_day = input("What days do you water this plant? Please provide each day one at a time. Type 'done' when you are finished. Water this plant on:\n") watering_days = [] valid_days = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"] while watering_day.lower() != "done": if watering_day.lower() in valid_days: watering_days.append(watering_day.lower()) watering_day = input("And:\n") else: watering_day = input("Sorry, that is not a valid day of the week. Please try again.\n") print("\nGreat! You are all done making your plant.") # 返回创建好的植物实例 return Plant(name, location, watering_days) # 用来存储所有植物的列表 plants = [] # 示例:循环添加植物 while True: add_choice = input("\nDo you want to add a plant? (yes/no)\n").lower() if add_choice == "yes": new_plant = create_plant() plants.append(new_plant) print(f"Added plant: {new_plant.name}") elif add_choice == "no": break else: print("Please enter 'yes' or 'no'.") # 查看所有植物示例 print("\nYour plants list:") for idx, plant in enumerate(plants, 1): print(f"Plant {idx}:") print(f" Name: {plant.name}") print(f" Location: {plant.location}") print(f" Watering days: {', '.join(plant.watering_days)}")
为什么不推荐动态生成变量名?
- 动态生成的变量(比如用
globals()[f"plant{count}"] = Plant(...))会让代码变得混乱,后续很难追踪和操作这些变量 - 容器(列表/字典)是Python中管理多个同类对象的标准方式,更符合Python的编程习惯,也更容易维护和扩展(比如后续要保存到文件、筛选特定植物都更方便)
内容的提问来源于stack exchange,提问作者Ewan Weir
相关产品推荐
相关产品推荐

