在Python中使用类

时间:2015-02-16 00:36:30

标签: python list class python-2.7

如果我有5条相关数据,我认为使用类来有效地对数据进行排序是合理的。但是,我需要将这些变量添加到列表中。

如果我有班级"学生(姓名,年级,出勤率)",并且我将这些值附加到列表中,那会是什么样的?

1 个答案:

答案 0 :(得分:2)

# student class, inits with name and student id
class Student:
    def __init__(self,name,grade, attendance):
        self.name = name
        self.grade = grade
        self.attendance = attendance
    def __str__(self):
        return self.name

# list of students    
students = []

# creates two students
s1 = Student('terry', 99, 99)
s2 = Student('jack', 42, 1)

# add students in the list
students.append(s1)
students.append(s2)
print students