gpt4 book ai didi

python - 添加一个列表类

转载 作者:太空宇宙 更新时间:2023-11-04 00:10:49 25 4
gpt4 key购买 nike

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 方法中,我将如何实现一个列表(不能将其添加到初始化方法中)?该列表需要与对象相关联,以便稍后我可以从该列表中删除学生。

最佳答案

您可以将其添加到 __new__ 方法中:

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

关于python - 添加一个列表类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52533408/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com