在Python 3.43中定义类方法

时间:2016-04-06 20:50:58

标签: python-3.x

我正在尝试定义一个名为Student的班级,其名称,ID号,考试成绩和考试成绩的平均值。当我运行程序时,一切都有效,除了在将新分数附加到班级中的原始分数列表后打印测试分数平均值。它保持原始平均值“未定义”,我无法弄清楚它为什么不更新。

class Student:

"""The Student class stores the first and last name of a student,
   as well as all of their exam scores and overall average."""

def __init__(self, Id, first='', last=''):
    """Create a student object (e.g., Student(123654, Jane, Doe))"""
    self.Id = Id
    self.first_name = first
    self.last_name = last
    self.scores = []
    self.average = 'Undefined'

def getId(self):
    """Retrieves student's Id number"""
    return self.Id

def getfirst(self):
    """Retrieves student's first name"""
    return self.first_name

def getlast(self):
    """Retrieves student's last name"""
    return self.last_name

def getscore(self):
    """Retrieves list of student's test scores"""
    return self.scores

def getaverage(self):
    """Retrieves student's average test score"""
    return self.average

def add_score(self, score):
    """Updates student's list of test scores"""
    self.scores.append(score)
    return self.scores

def calculate_average(self):
    """Updates student's average test score using updated list of scores"""
    self.average = sum(self.scores) / len(self.scores)
    return self.average

def __str__(self):
    """Organizes student's information into a printable statement"""
    return "ID: " + self.Id + "    Name: " + self.first_name + " " + \
                   self.last_name + "    Average Score: " + self.average

def main():

print('This program reads student data from a file, prompts the')
print('user for the total number of exams completed, and outputs ')
print('the average score for each student.')


infile = open("student_data.txt", "r")
student_list = []

num_exams = int (input('Enter the number of exams completed: '))

for line in infile:
    Id, first, last = line.split()
    student = Student(Id, first, last)
    print('Enter scores for student', Id)
    for i in range(num_exams):
        score = int (input('Enter an exam score: ')) 
        student.add_score(score)
    student_list.append(student)

infile.close()

for student in student_list:
    student.getscore
    student.calculate_average
    student.getaverage
    print(student)

main()的

2 个答案:

答案 0 :(得分:1)

这是更多Pythonic类的定义:

from math import nan
from statistics import mean, StatisticsError

class Student(object):
    """The Student class stores the first and last name of a student,                                                                                                                                       
    as well as all of their exam scores and overall average."""

    def __init__(self, Id, first='', last=''):
        """Create a student object (e.g., Student(123654, Jane, Doe))"""
        self.Id = Id
        self.first = first
        self.last = last
        self.scores = []

    def __repr__(self):
        """Organizes student's information into a printable statement"""
        return "{0.__class__.__name__}({0.Id}, '{0.first}', '{0.last}', {0.average})".format(self)

    def __str__(self):
        """Organizes student's information into a printable statement"""
        return "{0.__class__.__name__}({0.Id}, '{0.first}', '{0.last}', {0.average})".format(self)

    @property
    def average(self):
        try:
            return mean(self.scores)
        except StatisticsError:
            return nan

    def add_score(self, score):
        """Updates student's list of test scores"""
        self.scores.append(score)

通过使用@property装饰器,self.average是一个可以自行计算的属性。这有助于避免"已self.average已更新?"的问题,因为所有计算都是由属性本身完成的。此外,如果没有分数,您可以使用nan(非数字)。

答案 1 :(得分:0)

有些事情让我觉得需要解决的是你没有在最后一个循环中调用类方法。

for student in student_list:
    student.calculate_average()
    print(student)

其他方法是不必要的,因为(我假设)你只想打印值,而不是将它存储在变量中。