【问题标题】:Using classes in Python在 Python 中使用类
【发布时间】:2015-04-16 11:09:25
【问题描述】:

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

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

【问题讨论】:

    标签: python list class python-2.7


    【解决方案1】:
    # 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
    

    【讨论】:

    • 谢谢!!你最好!
    • 如果我有未知数量的学生必须通过学生班,这将如何改变?
    • 您只需遍历学生,然后让每个元素成为学生的实例,然后推送到学生列表。
    猜你喜欢
    • 2013-04-13
    • 2021-01-06
    • 1970-01-01
    • 1970-01-01
    • 2012-06-27
    • 1970-01-01
    • 1970-01-01
    • 2016-06-17
    • 2021-12-04
    相关资源
    最近更新 更多