从类中获取最早/最晚的年份值,可以通过以下步骤实现:
以下是一个示例代码:
class Year:
def __init__(self):
self.years = []
def addYear(self, year):
self.years.append(year)
def getEarliestYear(self):
earliestYear = self.years[0]
for year in self.years:
if year < earliestYear:
earliestYear = year
return earliestYear
def getLatestYear(self):
latestYear = self.years[0]
for year in self.years:
if year > latestYear:
latestYear = year
return latestYear
def getYearRange(self):
earliestYear = self.getEarliestYear()
latestYear = self.getLatestYear()
return f"Earliest year: {earliestYear}, Latest year: {latestYear}"
# 示例用法
yearObj = Year()
yearObj.addYear(2000)
yearObj.addYear(1990)
yearObj.addYear(2010)
yearObj.addYear(1980)
print(yearObj.getYearRange())
输出结果为:Earliest year: 1980, Latest year: 2010
在这个示例中,我们创建了一个名为"Year"的类,使用addYear方法向年份列表中添加年份值。然后,我们使用getEarliestYear和getLatestYear方法获取最早和最晚的年份值,并在getYearRange方法中返回结果。最后,我们创建了一个Year对象,添加了几个年份值,并打印了最早和最晚年份值的范围。
请注意,这只是一个示例,实际应用中可能需要根据具体需求进行适当的修改和扩展。
领取专属 10元无门槛券
手把手带您无忧上云