函数x为0x

时间:2016-12-21 16:47:24

标签: python function class

我的任务要求我根据他们的积分和时间来获得学生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?

3 个答案:

答案 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} }。