2
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            

For the method add_student, how would i implement a list if it not in the init method, (CANT ADD IT TO THE INIT METHOD)? The list need to be connected with the object so later on i can remove students from that list.

3
  • Why can't you add a list in the __init__ method? Commented Sep 27, 2018 at 9:13
  • Its a requirement for the question. Commented Sep 27, 2018 at 9:15
  • 2
    @Michael That's a totally stupid requirement that forces the student to go against good practices. You can go tell your teacher that no serious professional developper would do that, and that such code wouldn't pass a code review. Commented Sep 27, 2018 at 9:39

3 Answers 3

2

You can add it in the __new__ method instead:

class Course:
    def __new__(cls, *args, **kwargs):
        course = super(Course, cls).__new__(cls)
        course.students = []
        return course
Sign up to request clarification or add additional context in comments.

3 Comments

Arf ! very creative work-around for a totally silly requirement !-)
now the teacher knows the student is cheating. But yeah. Only sound alternative. Or was it what the teacher wanted? far-fetched.
@Aran-Fey True. Edited as suggested then. Thanks.
1

naive method: try if the member exists, catch the attribute error, and create it if doesn't exist.

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

better use a "getter" instead to make sure the list is created when you access it from whatever method:

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

then add_student becomes:

def add_student(self, student_id):
    self.get_list().append(student_id)

of course adding it to __init__ is better if you don't have some strange constraints...

4 Comments

This is not a good answer because there's no guarantee that the add_student method is always called before the list is accessed by some other methods.
Yes it's better, although having all other methods call this method is not going to be very pretty. Not going to upvote this but I've removed my downvote. Thanks for the update.
@blhsing np, it's not worth many upvotes in the first place because it's not wise not to initialize the variable in __init__. Stupid homework requirements...
Absolutely. Quite a silly requirement to begin with. Still a somewhat interesting exercise in finding workarounds though.
0

You can initialize the list with a property getter, so that it would be initialized whenever it is first accessed:

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

8 Comments

The setter is useless and (imho) even harmful here.
Can you elaborate?
If you make _students an implementation ("protected") attribute - which is what the single leading underscode means, and which is the right thing to do here (the client code has no business knowing how students are "stored" in the Course objects - this might as well use a database of any kind, or a dict, or a set, or whatever...), then you don't want to allow client code to overwrite _students.
That's what I thought you'd say, but seeing how the OP has all the other attributes named without a leading underscore I'm just here trying to make students as available as the other attributes. Also, if I didn't have a setter, then other methods would need to set _students directly, which may not have been initialized. This prevents other methods from using list comprehension to implement operations such as removing students matching certain condition from the course, and can only modify the list in-place, which may not be ideal because lists are inefficient at in-place removal.
"Also, if I didn't have a setter, then other methods would need to set _students directly" => how would it be a problem ? That's ok for a method to directly access implementation attributes of it's own class/instance. But anyway: the base problem is, of course, the totally inept requirement to not creates self._students in the initializer.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.