【问题标题】:int and string errors in the class file in PythonPython 中的类文件中的 int 和字符串错误
【发布时间】:2016-07-20 12:03:47
【问题描述】:

我正在编写一个 python 程序,其中有 3 个文件。一个是主文件,一个是类文件,一个是数据文件。数据文件从2个文本文件中读取数据并拆分整理数据供类和主文件使用。无论如何,我已经完成了数据和主文件,但我遇到了类文件的问题。这是一个一般的字符串格式问题,但我无法理解我可以做些什么来解决它。我收到错误

“文件”/Users/admin/Desktop/Program 6/FINAL/classFile.py”,第 83 行, 在代表 if len(self._birthDay[0])

【问题讨论】:

  • self._birthDay 是字符串吗?你什么时候收到这个错误?
  • 你应该避免在 __repr__ 方法中修改对象,而不是更新一些缓存或其他东西。
  • 为了更清晰,我已经更新并添加了我的主文件和数据文件。

标签: python string class python-3.x methods


【解决方案1】:

在我看来,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)) 这将相当准确,不会太复杂。

【讨论】:

  • 很抱歉。为了更清楚,我现在添加了主文件和数据文件。
  • @JakeMeyer 更新了我的答案。
  • 谢谢,但是如果我使用这种方法,我将如何更新 def currentAge(self) 方法中的 if else 语句? if myMonth
  • datetime 对象有 year、month 和 day 属性,如果你愿意,但你可以用我在答案末尾建议的一个衬里替换整个方法只关心是否合理准确。
  • 要清楚,你可以做today = datetime.datetime.today(),然后是self._birthDay.month <= today.month,等等。dateutil还有一个模块relativedelta可以帮助抽象出这种事情,所以你可以做@987654350 @
【解决方案2】:

使用string formatting,而不是字符串连接,它更更简洁:

return "{} {} (# {} ) GPA {:0.2f}".format(
    self._first, self._last, self._techID, self.currentGPA()
)

另外,如果你使用这种格式,它会自动为你转换类型

【讨论】:

  • 那我应该如何写 if elif 语句呢?
  • 你可以考虑'3'.zfill(2)
  • 我刚刚注意到您的生日有时是一个数字。 '{!s:0>2}'.format(3) 试穿尺寸。
  • 我们不允许zfill。有没有办法可以使用我当前的 if elif 语句?另外,我添加了我的 main 和 getData 文件,这样你就可以看到程序实际在做什么。
【解决方案3】:

正如错误消息所述,len 对 int 没有意义。如果你想要其中的字符数,请先将其转换为str。

def __repr__(self):
    if len(str(self._birthDay[0]))<2:
        self._birthDay[0] = "0" + str(self._birthDay[0])
    elif len(str(self._birthDay[1]))<2:
        self._birthDay[1] = "0" + str(self._birthDay[1])
    return self._first + " " + self._last + " (#" + self._techID + ")\nAge: " + str(self.currentAge()) + \
           " (" + str(self._birthDay[0]) + "/" + str(self._birthDay[1]) + "/" + str(self._birthDay[2]) + ")" + \
           "\nGPA: %0.2f" % (self.currentGPA()) + " (" + str(self._totalCredits) + " Credits" + ")\n"

【讨论】:

  • 很抱歉。为了更加清晰,我现在添加了主文件和数据文件。
  • 它给了我错误文件“/Users/admin/Desktop/Program 6/FINAL/classFile.py”,第 84 行,在 repr self._birthDay[ 0] = "0" + str(self._birthDay[0]) TypeError: 'tuple' object does not support item assignment
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-12
  • 2023-03-25
  • 1970-01-01
  • 1970-01-01
  • 2015-10-25
  • 2017-03-29
相关资源
最近更新 更多