首页 > 解决方案 > 如何在python中显示错误的子类中调用一个类中的一个函数?

问题描述

 class Student:
     def __init__(self,name,a,b,c):
         self.name=name
         self.a=a
         self.b=b
         self.c=c
         def totalscore(self):
             self.score=self.a+self.b+self.c/100
             return score
 class Result:
     def __init__(self,stlist):
         self.stlist=stlist
     def grade(self):
         for i in stlist:
             x=i.totalscore()
             if(x>80):
                 print('A')
             elif(x>60 and x<80):
                 print('B')
             elif(x>40 and x<60):
                 print('c')
             else:
                 return None
 if __name__=='__main__':
     n=int(input('Enter  the input student'))
     stlist=[]
     for i in range(n):
         name=input('enter the name of student')
         a=int(input())
         b=int(input())
         c=int(input())
         stlist.append(Student(name,a,b,c))
     u=Result(stlist)
     u.grade()

我得到一个NameError

Traceback (most recent call last)
<ipython-input-3-e20009ff9dd6> in <module>
     32         stlist.append(Student(name,a,b,c))
     33     u=Result(stlist)
---> 34     u.grade()`enter code here`
     35 
     36 
<ipython-input-3-e20009ff9dd6> in grade(self)
     13     def grade(self):
     14         for i in stlist:
---> 15             x=i.totalscore(score)
     16             if(x>80):
     17                 print('A')
NameError: name 'score' is not defined**

标签: pythonclass

解决方案


如果你想调用它,该方法totalscore()应该在外面。__init__()

class Student:
    def __init__(self,name,a,b,c):
        self.name=name
        self.a=a
        self.b=b
        self.c=c

    def totalscore(self):
        score=self.a+self.b+self.c/100
        return score
        

class Result:
    def __init__(self,stlist):
        self.stlist=stlist
    def grade(self):
        for i in self.stlist:
            # Here you are calling the totalscore() function of Student
            x=i.totalscore()
            if(x>80):
                print('A')
            elif(x>60 and x<80):
                print('B')
            elif(x>40 and x<60):
                print('c')
            else:
                return None


推荐阅读