python - 添加一个列表类
问题描述
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
对于 add_student 方法,如果它不在init方法中,我将如何实现一个列表(不能将它添加到 INIT 方法中)?该列表需要与该对象连接,以便稍后我可以从该列表中删除学生。
解决方案
您可以将其添加到__new__
方法中:
class Course:
def __new__(cls, *args, **kwargs):
course = super(Course, cls).__new__(cls)
course.students = []
return course