在我看来,birthDay 是一个整数列表,而不是字符串列表。
如果你想确保它们都是字符串,你可以试试:
self._birthDay = list(map(str, birthDay))
或者,如果您知道它们都是字符串,则可以首先使用字符串格式化来避免这些len 检查:
self._birthDay = ['{:02d}'.format(x) for x in birthDay]
不过,更好的方法是将birthDay 表示为datetime.datetime 对象。假设它总是以 3 个整数的形式出现,月、日、年,你会这样做:
bmon, bday, byear = birthDay
self._birthDay = datetime.datetime(byear, bmon, bday)
那么你的__repr__ 就可以使用datetime.strftime 方法了。
编辑
为了响应您的更新,我认为您应该将from datetime import datetime 添加到getData 的顶部,然后不要解析月/日/年,而是使用:
birthDay = datetime.strptime(x[3], '%m/%d/%Y')
这将为您提供一个完整的 datetime 对象来表示生日(或者,您可以使用 datetime.date 对象,因为您不需要时间)。
然后您可以将 __repr__ 方法替换为:
def __repr__(self):
fmtstr = '{first} {last} (#{techid})\nAge: {age} ({bday})\nGPA: {gpa:0.2f} ({credits})'
bday = self._birthDay.strftime('%m/%d/%Y')
return fmtstr.format(first=self._first,
last=self._last,
age=self.currentAge(),
bday=bday,
gpa=self.currentGPA(),
credits=self._totalCredits)
哦,既然_birthDay 现在是datetime.datetime,您需要更新currentAge() 以返回int((datetime.datetime.now() - self._birthDay) / datetime.timedelta(days=365)) 这将相当准确,不会太复杂。