簡體   English   中英

Python中類文件中的int和字符串錯誤

[英]int and string errors in the class file in Python

我正在編寫一個有3個文件的python程序。 一個是主文件,一個是類文件,一個是數據文件。 數據文件從2個文本文件中讀取並拆分並排列數據,以供類和主文件使用。 無論如何,我已經完成了數據和主文件的全部工作,但是類文件卻遇到了問題。 它是一個通用的字符串格式問題,但是我無法理解我可以做些什么來修復它。 我收到錯誤

如果len(self._birthDay [0])<2,則代表文件“ / Files / Users / admin / Desktop / Program 6 / FINAL / classFile.py”,第83行,請代表repr :TypeError:類型為'int'的對象沒有len( )

使用字符串格式 ,而不是字符串連接,它干凈:

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

另外,如果您使用這種格式,它將自動為您轉換類型

在我看來, 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))准確而又不會太復雜。

如錯誤消息所述, 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"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM