class courseInfo(object):
def __init__(self, courseName):
self.courseName = courseName
self.grade = "No Grade"
def setGrade(self, grade):
if self.grade == "No Grade":
self.grade = grade
def getGrade(self):
return self.grade
class edx(object):
def __init__(self, courses):
self.myCourses = []
for course in courses:
self.myCourses.append(courseInfo(course))
def setGrade(self, grade, course="6.01x"):
"""
grade:integer greater than or equal to 0 and less than or equal to 100
course: string
This method sets the grade in the courseInfo object named by `course`.
If `course` was not part of the initialization, then no grade is set, and no
error is thrown.
The method does not return a value.
"""
for crs in self.myCourses:
if crs.courseName == course:
crs.setGrade(grade)
def getGrade(self, course="6.02x"):
"""
course: string
This method gets the grade in the the courseInfo object named by `course`.
returns: the integer grade for `course`.
If `course` was not part of the initialization, returns -1.
"""
for crs in self.myCourses:
if crs.courseName == course:
return crs.getGrade()
else:
return -1
我上面代码的测试用例是:
> edX = edx( ["6.00x","6.01x","6.02x"] )
> edX.setGrade(100, "6.00x")
> edX.getGrade("6.00x")
> 100
到目前为止一切顺利,但正在运行edX.setGrade(50, "6.00x")
并且getGrade
仍然会返回100
。此外,设置6.01
和6.02
的分数似乎不起作用,getGrade
始终返回-1
。
非常感谢任何帮助指针!
(完全披露:这是一个在线课程。但我不认为这里有任何破坏者,我真的想了解发生了什么.Tks)
答案 0 :(得分:3)
当然它只运行一次,你就这样编码了:
def setGrade(self, grade):
if self.grade == "No Grade":
self.grade = grade
设置成绩后,测试self.grade == "No Grade"
不再成立。
getGrade()
方法确实存在问题:
for crs in self.myCourses:
if crs.courseName == course:
return crs.getGrade()
else:
return -1
如果第一个课程与名称不匹配,则返回-1
;你从那里的for
循环返回。也许您想在测试所有课程之后只返回-1
:
for crs in self.myCourses:
if crs.courseName == course:
return crs.getGrade()
return -1
现在for
循环只有在找到匹配的课程时才会中断,并且您不再为-1
以外的任何内容返回"6.00x"
。