我是新來的Python,我很困惑,爲什麼我得到一個覆蓋錯誤。我正在嘗試構建一個類網絡,並將其表示爲由BST代表的字典。字典中的鍵可以是具有值列表的課程對象的Student對象,也可以是具有值列表的學生的課程(字符串)。問題是,當分析課程是否在字典中時,它儘管是一個字符串對象,仍然使用Student類的平等。這裏是我的代碼:平等覆蓋問題
def getClassList():
ClassList = [] # an empty list to be filled from class.csv file
with open('lab6.csv', 'rb') as f: # access local file 'class.csv'
reader = csv.reader(f) # connects reader object to file
for row in reader: # reads one text line at a time
ClassList += [row] # .. and appends to the ClassList
return ClassList
class Student:
def __init__(self, lastname, firstname, favcolor):
# assert(True)
self.lastname = lastname
self.firstname = firstname
self.favcolor = favcolor
def __eq__(self, other):
assert(type(other) == type(self))
if (self.lastname == other.lastname and self.firstname == other.firstname and self.favcolor == other.favcolor):
return True
else:
return False
def __repr__(self):
return str(self.firstname)+' '+str(self.lastname)
class ClassNetwork:
def __init__(self):
#creating an empty graph
self.rep=Dictionary()
#using the getClassList function to get the necessary info to create the graph
classlist=getClassList()
#not using the first list since it doesn't contain info
classlist=classlist[1:]
#traversing the list of lists
for i in range(len(classlist)):
#constructing a new student from each list (Student object)
newStudent=Student(classlist[i][0],classlist[i][1],classlist[i][3])
#getting a course from each list (str type)
newCourse=str(classlist[i][2])
#HANDLING THE COURSE
#checking if the course exists or not
if self.rep.lookup(newCourse)=='No entry':
#if not, add it
self.rep.put(newCourse,[newStudent])
#if course already exists, update the student list
else:
upCo=self.rep.lookup(newCourse)+[newStudent]
self.rep.put(newCourse,upCo)
#HANDLING THE STUDENT
#checking if the student exists or not
if self.rep.lookup(newStudent)=='No entry':
#if not, add them - use put method
self.rep.put(newStudent,[newCourse])
#if the student already exists, update course list
else:
#updated value=old courses+the new course
upSt=self.rep.lookup(newStudent)+[newCourse]
self.rep.put(newStudent,upSt)
def __repr__(self):
return repr(self.rep.rep.inorderlist())
錯誤:
Exception raised:
Traceback (most recent call last):
File "/usr/lib/python2.7/doctest.py", line 1315, in __run
compileflags, 1) in test.globs
File "<doctest __main__[0]>", line 1, in <module>
CN = ClassNetwork()
File "/homes/user/cs106/Lab 6/lab6.py", line 93, in __init__
if self.rep.lookup(newStudent)=='No entry':
File "/homes/user/cs106/Lab 6/lab6.py", line 181, in lookup
return self.rep.lookup(key)
File "/homes/user/cs106/Lab 6/BST.py", line 81, in lookup
elif self.root()[0] == key:
File "/homes/user/cs106/Lab 6/lab6.py", line 56, in __eq__
assert(type(other) == type(self))
AssertionError
你最想如果到'返回FALSE'了'學生'不匹配一個字符串。目前,您只使用'assert',因此當比較返回False時爲什麼會引發'AssertionError'。 –
謝謝你的幫助!它解決了我的問題。 – Silvia
我在下面重複了我的回答 - 如果您可以將此標記爲接受的答案,那將非常棒。謝謝。 –