我是新来的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
我在下面重复了我的回答 - 如果您可以将此标记为接受的答案,那将非常棒。谢谢。 –