首页 > 解决方案 > 列表中的对象列表中的 Python 对象初始对象

问题描述

我正在尝试组织越来越具体的数据,但我不确定如何以及何时初始化某些对象。

历史有一份年表。Years 有一个季节列表。Seasons 有一个月份列表。

这是我的班级定义

class History:
    def __init__(self):
        self.years = []

    def add_year(self, year):
        self.years.append(year)

class Years:
    def __init__(self, number):
        self.number = number
        self.seasons = []

    def add_season(self, season):
        self.seasons.append(season)

class Seasons:
    def __init__(self, name, day):
        self.name = name
        self.date = day
        self.months = []

    def add_month(self, month)
        self.months.append(month)

class Month:
    def__init__(self, name)
    self.name = name

#initialize History
h = History()

year = ["2015", "2016", "2017", "2018"]

for x in year:
    #add each year to history years[] list (does this also create year objects?)
    h.add_year(x)

    #add each season to the seasons[] list(does this in turn create my seasons objects?)

    h.x.add_season("fall", "265")
    h.x.add_season("spring","81")

    #add months to months[] list in season class
    h.x.fall.add_month("September")
    h.x.fall.add_month("October")

标签: pythonlistobject

解决方案


类的结构方式,您将需要以某种相反的顺序创建对象。应该可以帮助您的相关代码在这里:

# Initialize history
h = History()

x = "2018"
# let's start with a year object first
new_year = Year(x)

# we need a new season: let's create it
new_season = Season("fall", "265")

# a season needs months: we create them as we add them
new_season.add_month(Month("September"))
new_season.add_month(Month("October"))

# Now you have a complete season object: add it to the year
new_year.add_season(new_season)

# Now you have a complete year: add it to history
h.add_year(new_year)

这可能会变得非常复杂,但可以工作。我的建议是检查您打算如何将这个“机器”提供给 create History,然后将其中的一些包装在Year类或其他一些函数中。

设计的另一个重要部分是一旦准备好您打算如何使用History,因为这将决定一些数据结构而不是其他数据结构。

旁注:我更喜欢类的单数名称,所以YearsSeasonsMonths成为YearSeasonMonth:我认为这更能代表它们是一个单一的对象。


推荐阅读