【问题标题】:Finding average and totalNum in Python Class在 Python 类中查找 average 和 totalNum
【发布时间】:2014-04-24 21:16:18
【问题描述】:

我第一次尝试使用类在 Python 中编写一个程序,并且大部分都已经弄清楚了。在这个项目中唯一让我难过的是如何计算为该项目创建的学生数量。我以为我可以创建一个变量“numStudents”并执行 ole“x = x + 1”,但由于某种原因它不适用于类。有人知道解决方案吗?我还需要计算平均年龄,而我的列表似乎不起作用。

numStudents = 0
ageList = list()
class student(object):
    def __init__(self, name, stuID, age):
        self.name = name
        self.stuID = stuID
        self.age = age
    def student_display(self):
        numStudents = numStudents + 1
        stuID = str(self.stuID)
        age = str(self.age)
        ageList.append(self.age)
        print "This student's name is " + self.name + ", his student ID is " + stuID + ", and his age is " + age + "."

student1 = student("Justin", 10001, 21)
student2 = student("Charles", 10002, 23)
student3 = student("Erik", 10003, 20)
student4 = student("The Doctor", 99999, 22)
student5 = student("Steven", 10004, 21)
student6 = student("Melissa", 10005, 19)
student7 = student("Sarah", 10006, 21)
student8 = student("Eren", 10007, 18)
students = 0                                           #Can't figure out how to get rid of the "NONE" that keeps printing after every statement

print student1.student_display()
print student2.student_display()
print student3.student_display()
print student4.student_display()
print student5.student_display()
print student6.student_display()
print student7.student_display()
print student8.student_display()

print "There are " + numStudents + " students in the class."
average = 0
sum = 0
for n in ageList:
    sum = sum + n
average = sum/len(ageList)
print "The average age in the class is " + average + "."

【问题讨论】:

    标签: python list class


    【解决方案1】:

    您得到None 打印输出的原因是您正在打印student_display 的返回值,即None,因为它不返回任何内容。你已经在方法内部进行了打印,无需再次进行。

    你的num_studentsageLists不起作用的原因是你需要在student_display中添加一个global关键字:

    def student_display(self):
        global numStudents
        global ageLists
        numStudents = numStudents + 1
    

    但是,话虽如此,这样做真的很糟糕。有很多方法可以解决这个问题,但对于 numStudents 的情况,您可以简单地创建一个学生列表,如下所示:

    students = [
                student("Justin", 10001, 21),
                ...
                student("Eren", 10007, 18)]
    

    然后像这样打印所有学生:

    for student in students:
        student.student_display()
    

    对于计算平均年龄:

    ages = [student.age for student in students]
    print('Average Age Is: {}'.format(sum(ages)/len(ages))
    

    【讨论】:

    • 哇,这非常有帮助和洞察力。谢谢!
    猜你喜欢
    • 2013-05-08
    • 2022-12-03
    • 2017-11-30
    • 2017-09-13
    • 1970-01-01
    • 2021-03-27
    • 1970-01-01
    • 2021-11-20
    • 1970-01-01
    相关资源
    最近更新 更多