Python 0x处的函数x
我有一项作业,要求我根据学生的分数和课时获得平均成绩。我很难让python在我创建的类中返回gpa。这是一节课:Python 0x处的函数x,python,function,class,Python,Function,Class,我有一项作业,要求我根据学生的分数和课时获得平均成绩。我很难让python在我创建的类中返回gpa。这是一节课: class Student: """Creates a student with the requirements of names, hours, and points, then calculates and returns the specific student's gpa""" def __init__(self, name, hours, po
class Student:
"""Creates a student with the requirements of names, hours, and points, then
calculates and returns the specific student's gpa"""
def __init__(self, name, hours, points):
self.name = name
self.hours= float(hours)
self.points = float(points)
self.gpa = self.points/self.hours
def getname(self):
"""Gets the name of the student"""
return self.name
def getpoints(self):
"""Get the points of the student"""
return self.points
def gethours(self):
"""Get the Hours of the student"""
return self.hours
def gpa(self):
"""Gets the GPA of the student"""
return self.gpa
我使用的代码是:
def main():
filename = 'student.txt'
infile = open(filename, 'r')
gpa = []
for line in infile:
name, hours, points = line.split('\t')
Student(name,hours,points)
gpa.append(Student.gpa)
print(gpa)
main()
当运行该列表时,该列表将返回以下内容
[,,,,,,]
我如何着手解决这样的问题,以便它实际返回gpa?您需要保存Student()的实例,并在gpa调用中使用它。您实际上也不需要gpa函数(它将覆盖在init中设置的gpa值)。因此,删除def gpa(self):函数并附加s.gpa。类似于s=Student(…)和gpa.append(s.gpa)的内容
您必须将
Student
构造函数的结果保存到一个变量中,并且您必须实际调用函数gpa
以获得其结果您将Student.gpa
附加到循环中的列表中,这是一个函数(aka方法)学生的——这也是为什么它一次又一次地具有相同的值。您需要创建一个Student
实例,即Student=Student(name,hours,points)
,然后调用它的gpa()
方法并将返回的结果追加到列表中,即gpa.append(Student.gpa())
,为什么会有多余的getter?Python不是Java。您可以自己打印列表。尝试“”。加入(gpa)你问题的标题是什么意思?你的self.gpa
getter正在跟踪self.gpa
字段。@JackManey在Python中看到这些类型的getter和setter让我很痛苦,OP可能是在一些介绍性的CS课程中,这就是在这样的课程中编写类的方式(事实上,我打赌直到最近课程还是用Java教授的)。除了你没有看到self.gpa()
函数将返回什么之外。。。提示:不是用户认为它返回的gpa函数正在返回自己。。。所以这无关紧要
gpa = []
for line in infile:
name, hours, points = line.split('\t')
s = Student(name,hours,points)
gpa.append(s.gpa())