在 Python 中使用 类
Using classes in Python
如果我有 5 条相关数据,我认为使用 class 可以有效地对数据进行排序。但是,我需要将这些变量添加到列表中。
如果我有 class "student(name, grade, attendance)",并且我将这些值附加到列表中,那会是什么样子?
# 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
如果我有 5 条相关数据,我认为使用 class 可以有效地对数据进行排序。但是,我需要将这些变量添加到列表中。
如果我有 class "student(name, grade, attendance)",并且我将这些值附加到列表中,那会是什么样子?
# 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