我的任务要求我根据他们的积分和时间来获得学生gpa。我无法让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, 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()
运行时,列表会返回
行
[<function gpa at 0x04AE5780>, <function gpa at 0x04AE5780>, <function gpa at 0x04AE5780>, <function gpa at 0x04AE5780>, <function gpa at 0x04AE5780>, <function gpa at 0x04AE5780>, <function gpa at 0x04AE5780>, <function gpa at 0x04AE5780>, <function gpa at 0x04AE5780>, <function gpa at 0x04AE5780>, <function gpa at 0x04AE5780>, <function gpa at 0x04AE5780>, <function gpa at 0x04AE5780>, <function gpa at 0x04AE5780>, <function gpa at 0x04AE5780>]
我将如何解决这样的问题,以便实际返回gpa?
答案 0 :(得分:1)
您需要保存Student()的实例并在您的gpa调用中使用它。你也真的不需要gpa功能(它覆盖了 init 中设置的gpa值)。因此,删除def gpa(self):function并附加s.gpa。像s = Student(...)和gpa.append(s.gpa)
之类的东西答案 1 :(得分:0)
gpa = []
for line in infile:
name, hours, points = line.split('\t')
s = Student(name,hours,points)
gpa.append(s.gpa())
您必须将Student
构造函数的结果保存到变量中,并且您必须实际调用函数gpa
才能获得结果
答案 2 :(得分:0)
您将Student.gpa
附加到循环中的列表中,这是class Student
的一个函数(也称为方法) - 这也是为什么它与...相同的值。过度。您需要创建一个Student
实例,即student = Student(name, hours, points)
,然后调用其gpa()
方法,并将其返回的结果追加到列表中,即{{1} }。