列表内对象列表内的Python对象起始对象

时间:2018-10-30 18:06:05

标签: python list object

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

历史记录有年份列表。年有一个季节列表。季节有一个月列表。

这是我的班级定义

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")

1 个答案:

答案 0 :(得分:0)

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

# 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)

这可能会令人费解,但可以解决。我的建议是检查计划如何喂食此“机器”以创建History,然后将其中一些包装在Year类或其他函数中。

设计的另一个重要部分是计划如何准备好使用History,因为这将指示某些数据结构,而不是其他数据结构。

旁注:我更喜欢为类使用单数名称,因此YearsSeasonsMonths变成了YearSeasonMonth:我认为这更能代表他们是单个对象。