打印有关类中对象的值(Python)

时间:2018-07-12 07:23:57

标签: python python-3.x class object

我已编写此代码来组织学生的成绩。如何通过用户输入(在python中使用不确定的数字)接收学生分数,并使用附带的“ top”类对象输出平均分最高的学生?

在python编码方面,我是一个初学者,请帮助我解决此问题。

class Student:
    def __init__(self, n, g):
        self.name = n
        self.gender = g
        self.grades = []

    def add(self,grade):
        #do something.
        self.grades.append(grade)

    def avg(self):
        #do something.
        #return avg_grade
        return 0

    def fcount(self):
        #do something.
        #return fail_count
        return 0

    def __str__(self):
        return "Name:%s Avg:%.2f Subject(s) less than 60:%d" % (self.name, self.avg(), self.fcount())

    @classmethod
    def top(cls, *students):
        tops = students[0]
        for s in students:
            print(s.grades)
        return tops

s1 = Student("Tom","M")
s2 = Student("Jane","F")
s3 = Student("John","M")
s4 = Student("Ann","F")
s5 = Student("Peter","M")
s1.add(80)
s1.add(90)
s1.add(55)
s1.add(77)
s1.add(40)
s2.add(58)
s2.add(87)
s3.add(100)
s3.add(80)
s4.add(40)
s4.add(55)
s5.add(60)
s5.add(60)

print(str(s1))
print(str(s2))
print(str(s3))
print(str(s4))
print(str(s5))
tops = Student.top(s1,s2,s3,s4,s5)
print("Student w/ Highest Score:{} ; Average Score: {}".format(tops.name, tops.avg()))

输出:

Name:Tom Avg:0.00 Subject(s) less than 60:0
Name:Jane Avg:0.00 Subject(s) less than 60:0
Name:John Avg:0.00 Subject(s) less than 60:0
Name:Ann Avg:0.00 Subject(s) less than 60:0
Name:Peter Avg:0.00 Subject(s) less than 60:0
[80, 90, 55, 77, 40]
[58, 87]
[100, 80]
[40, 55]
[60, 60]
Student w/ Highest Score:Tom ; Average Score:0

2 个答案:

答案 0 :(得分:0)

avg方法更改为此:

@property
def avg(self):
  return sum(self.grades) / float(len(self.grades))

@property是修饰符和语法糖,使此方法成为“ getter”。或者,如果您愿意,也可以将其视为“计算属性”。这对解决您的问题并不重要,但它是构建类的好方法。

您不需要top作为类方法。由于将所有对象(包括“自身”)传递给它,因此可以使此方法成为主要功能。或者,您也可以创建另一个名为Classroom的类,它具有属性students,将是所有Student对象。然后,您还可以在那里使用一个名为top_student的类方法。但目前,以下功能也可能是主要功能:

def top(*students):
    top_student = students[0]

    for student in students:
        if student.avg > top_student.avg:
          top_student = student

    return top_student

将其添加到您的代码中:

class Student:
    def __init__(self, n, g):
        self.name = n
        self.gender = g
        self.grades = []

    def add(self,grade):
        #do something.
        self.grades.append(grade)

    @property
    def avg(self):
        return 0 if len(self.grades) == 0 else sum(self.grades) / float(len(self.grades))

    def fcount(self):
        #do something.
        #return fail_count
        return 0

    def __str__(self):
        return "Name: {}, Avg: {:2}".format(self.name, self.avg)

class Classroom:
    def __init__(self, *students):
        self.students = students

    def input_grades_per_student(self):
        for student in self.students:
            while True:
                grade = input("Enter {}'s grade (or leave empty to continue to the next student): ".format(student.name))
                if len(grade) == 0:
                    print()
                    break

                try:
                   grade = float(grade)
                   student.add(grade)
                except ValueError:
                   print("That's not a number.")

    @property
    def top_student(self):
        top_student = self.students[0]

        for student in self.students:
            if student.avg > top_student.avg:
                top_student = student

        return top_student

s1 = Student("Tom","M")
s2 = Student("Jane","F")
s3 = Student("John","M")
s4 = Student("Ann","F")
s5 = Student("Peter","M")

classroom = Classroom(s1, s2, s3, s4, s5)
classroom.input_grades_per_student()
print("Student with highest score:{} ; Average score: {}".format(classroom.top_student.name, classroom.top_student.avg))

在这里,我还创建了一个Classroom类,使内容更易于阅读。

输出:

Enter Tom's grade (or leave empty to continue to the next student): 15
Enter Tom's grade (or leave empty to continue to the next student): 20
Enter Tom's grade (or leave empty to continue to the next student): 

Enter Jane's grade (or leave empty to continue to the next student): 12
Enter Jane's grade (or leave empty to continue to the next student): 13
Enter Jane's grade (or leave empty to continue to the next student): 

Enter John's grade (or leave empty to continue to the next student): 16
Enter John's grade (or leave empty to continue to the next student): 

Enter Ann's grade (or leave empty to continue to the next student): 17
Enter Ann's grade (or leave empty to continue to the next student): 

Enter Peter's grade (or leave empty to continue to the next student): 18
Enter Peter's grade (or leave empty to continue to the next student): 

Student with highest score:Peter ; Average score: 18.0

答案 1 :(得分:0)

查看scan_gradesavgtop方法:

class Student:
    def __init__(self, n, g):
        self.name = n
        self.gender = g
        self.grades = []

    def scan_grades(self):
        subject_count = input('Enter number of subjects: ')
        for i in range(subject_count):
            score = float(input('Enter score: ')
            self.add(score)

    def add(self,grade):
        #do something.
        self.grades.append(grade)

    def avg(self):
        return sum(self.grades) / len(self.graders)

    def fcount(self):
        #do something.
        #return fail_count
        return 0

    def __str__(self):
        return "Name:%s Avg:%.2f Subject(s) less than 60:%d" % (self.name, self.avg(), self.fcount())

    @classmethod
    def top(cls, *students):
        top_student = max(students, key = lambda std: std.avg())
        return top_student
  • 您可以使用scan_grades方法扫描学生的成绩。
  • top方法使学生获得最大的平均分。它用
    1. maxdocumentation
    2. lambdadocumentation