You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中创建动态命名变量:植物管理练习程序开发疑问

解决方法:用容器存储植物实例

不要尝试动态生成不重复的变量名,这在Python里既不推荐也没必要,更好的方式是用列表或者字典来统一管理所有植物实例,这样既能避免覆盖问题,还能方便后续对植物进行查询、修改等操作。

具体实现步骤

  1. 定义一个容器(比如列表plants = [])来保存所有植物实例
  2. 修改CreatePlant函数,让它返回创建好的Plant对象
  3. 每次调用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 02:18:10