python - 如何在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**
解决方案
如果你想调用它,该方法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
推荐阅读
- css - 分割颜色 SVG 线
- python - 适当的条件循环
- python - Python 使用字符串格式运算符打印两个列表
- java - 如何发现列表中缺少的渐进式算术数
在 Java 8 中? - java - Netbeans 8.2 和 JDK 8 中的“无法在文件夹中创建文件夹 s37”
- java - 登录时用户帐户被锁定
- reactjs - 渲染 ReactJS - './images/0.jpg' 有效.. 但 property.image 没有?
- dictionary - 多个字符串到字典的转换
- java - 如何从 Java 的子目录中读取文件?
- tradier - 交易者历史 API 不适用于“$DJI”等索引符号