Python类Setter方法只能工作一次

时间:2015-08-11 08:36:23

标签: python

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.016.02的分数似乎不起作用,getGrade始终返回-1

非常感谢任何帮助指针!

(完全披露:这是一个在线课程。但我不认为这里有任何破坏者,我真的想了解发生了什么.Tks)

1 个答案:

答案 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"