Python 在类中添加列表

Python 在类中添加列表,python,Python,对于add_student方法,如果列表不在init方法中(无法将其添加到init方法),我将如何实现列表?该列表需要与对象连接,以便稍后我可以从该列表中删除学生 朴素方法:如果成员存在,请尝试,捕获属性错误,如果不存在,则创建属性错误 class Course: ''' A class representing a course offering that includes the following information about the course: sub

对于add_student方法,如果列表不在init方法中(无法将其添加到init方法),我将如何实现列表?该列表需要与对象连接,以便稍后我可以从该列表中删除学生

朴素方法:如果成员存在,请尝试,捕获属性错误,如果不存在,则创建属性错误

class Course:
    ''' 
    A class representing a course offering that includes the following
    information about the course: subject, course number, section,
    enrolment cap, lecture days, lecture start time, lecture duration 
    in minutes, and unique student numbers of the students enroled.
    If lectures occur on multiple days, they will all start at the same time.
    '''

    def __init__(self, subject, number, section, cap, days, start_time, dur):
        '''
        returns a new Course object with no students enroled, given
           the subject, number, section, cap, days, start_time, and dur
        __init__: Str Nat Nat Nat Str Time Nat -> Course
        requires: number is a 3-digit number, section > 0, cap > 0,
           days is string containing substrings representing the days
           of the week 'M', 'T', 'W', 'Th', 'F', where if the course is
           offered on more than one day, the days appear in order and
           are separated by a single dash. For example, 'M-T-Th'
           indicates the course is offered on Monday, Tuesday, and Th.
        '''
        self.subject = subject
        self.number = number
        self.section = section
        self.cap = cap
        self.days = days
        self.start_time = start_time
        self.dur = dur

    def add_student(self, student_id):
        '''
        adds a student to the course enrolment if there is room in the course
           if the number of students enroled already matches the 
           enrolment cap, then print the message "Course full"
           if the student is already enroled in the course, the there is no 
           change to the Course object, and the message "Previously enroled"
           is printed.
        add_student: Course Nat -> None
        Effects: Mutates self. May print feedback message.
        '''
        pass            
最好使用“getter”,以确保在通过任何方法访问列表时创建该列表:

def add_student(self, student_id):
    try:
        self.__list
    except AttributeError:
        self.__list = []
    self.__list.append(student_id)
然后
add_student
变成:

def get_list(self):
    try:
        self.__list
    except AttributeError:
        self.__list = []
   return self.__list

当然,如果没有一些奇怪的约束,将其添加到
\uuuuu init\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu>会更好…

您可以将其添加到
def add_student(self, student_id):
    self.get_list().append(student_id)

您可以使用初始化列表,以便在首次访问列表时对其进行初始化:

class Course:
    def __new__(cls, *args, **kwargs):
        course = super(Course, cls).__new__(cls)
        course.students = []
        return course

为什么你不能在
\uuuu init\uuuu
方法中添加一个列表?这是问题的一个要求。@Michael,这是一个完全愚蠢的要求,迫使学生违背良好实践。你可以去告诉你的老师,没有认真的专业开发人员会这么做,而且这样的代码不会通过代码审查。这不是一个好答案,因为不能保证在列表被其他方法访问之前总是调用
add\u student
方法。是的,这样更好,尽管让所有其他方法调用这个方法不会很好。我不打算投赞成票,但我已经取消了我的反对票。感谢您的更新。@blhsing np,首先它不值得进行多次升级表决,因为不在
\uuuu init\uuuu
中初始化变量是不明智的。愚蠢的家庭作业要求…绝对。这是一个相当愚蠢的要求。不过,在寻找解决方法方面,这仍然是一个有趣的练习。setter在这里是无用的,甚至是有害的。你能详细说明一下吗?如果你给学生们设置了一个实现(“protected”)属性,这就是单个代码的意思,在这里做什么是正确的(客户机代码不需要知道学生是如何“存储”在课程对象中的——这也可以使用任何类型的数据库,或dict,或set,或其他任何东西……),那么你就不想让客户端代码覆盖
\u students
。这就是我想你会说的,但是看到OP如何命名所有其他属性而不使用前导下划线,我只是想让
students
与其他属性一样可用。另外,如果我没有setter,那么其他方法也需要直接设置学生,可能尚未初始化。这会阻止其他方法使用列表理解来执行操作,例如从课程中删除符合特定条件的学生,并且只能就地修改列表,这可能不理想,因为就地删除列表效率低下。“此外,如果我没有设置器,那么其他方法将需要直接设置学生“=>这会是一个什么问题?对于一个方法来说,直接访问它自己的类/实例的实现属性是可以的。但是无论如何:基本问题当然是,不创建
self的要求是完全不合适的。学生们在初始化器中创建
。Arf!非常有创造性地解决一个完全愚蠢的要求!)现在老师知道这个学生作弊了。但是是的。唯一合理的选择。还是老师想要的?太牵强了。@AranFey是真的。按照当时的建议进行编辑。谢谢
class Course:
    @property
    def students(self):
        try:
            return self._students
        except AttributeError:
            self._students = []
            return self._students

    @students.setter
    def students(self, value):
        self._students = value