python - 列表中的对象列表中的 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")
解决方案
类的结构方式,您将需要以某种相反的顺序创建对象。应该可以帮助您的相关代码在这里:
# 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
,因为这将决定一些数据结构而不是其他数据结构。
旁注:我更喜欢类的单数名称,所以Years
,Seasons
和Months
成为Year
,Season
和Month
:我认为这更能代表它们是一个单一的对象。
推荐阅读
- sql - Oracle 选择不同的合并重复项
- java - 当blockingqueue为空时杀死消费者
- java - 在java中加密文件的内容而无需手动指定加密密钥
- reactjs - 在 REACT APP 中使用高效的缓存策略服务静态资产
- r - Opencage 包,无法进行批量地理编码工作
- performance - 将调试构建模式更改为发布构建模式时没有性能提升?
- html - 在 flexbox 中排序 flex 项目
- reactjs - 在 React.Js 中创建一个组件作为另一个组件的子组件
- amazon-web-services - 找不到来自 Route 53 的域的 IP 地址服务器
- python-3.x - 求解模型后获取 pyomo 变量的无值