I want to append different courses into two different classrooms, however it keeps adding the same courses to both of the classrooms.
This is my AddCourse function
Edited
I modified my code according to your suggestions.
class Classroom:
"""I omitted part of the class for brevity"""
def __init__(self, Seed = None, ClassroomId = None, FirstCourseStartTime = None, LastCourseEndTime = None, CourseList = [], ProfessorList = []):
self.setFirstCourseStartTime(FirstCourseStartTime)
self.setLastCourseEndTime(LastCourseEndTime)
self.setCourseList(CourseList)
self.setProfessorList(ProfessorList)
self.setSeed(Seed)
self.setClassroomId(ClassroomId)
def addCourse(self, Course):
self.CourseList.append(Course)
def setCourseList(self, List):
self.CourseList = List
#the statements below are from a different file to run the code/class above
Classroom1 = Classroom(Seed = os.urandom(1024/8), FirstCourseStartTime = 8, LastCourseEndTime = 19.75)
Classroom2 = Classroom(Seed = os.urandom(1024/8), FirstCourseStartTime = 8, LastCourseEndTime = 19.75)
# Adding the courses to the classrooms
Classroom1.addCourse(Course0)
Classroom1.addCourse(Course1)
Classroom1.addCourse(Course2)
Classroom1.addCourse(Course3)
Classroom1.addCourse(Course4)
Classroom1.addCourse(Course5)
Classroom1.addCourse(Course6)
Classroom1.addCourse(Course7)
Classroom2.addCourse(Course8)
Classroom2.addCourse(Course9)
Classroom2.addCourse(Course10)
Classroom2.addCourse(Course11)
Classroom2.addCourse(Course12)
Classroom2.addCourse(Course13)
Classroom2.addCourse(Course14)
Classroom2.addCourse(Course15)
It looks like your issue is that all instances of your class are dealing with the same list, since you are declaring it only once.
Here’s an example of your problem, without all the extra stuff that doesn’t matter:
When we use it, we see the behavior you described:
Prints:
To show that this is the same list, we can print the
idof each instance’s list:For me, this outputs this (though it likely different each time):
The problem line for you is
course_list=[]in__init__‘s param list. You’re defining the list there, then likely not copying it anywhere else. This means whenever you append to the list, it’s always the same list you are appending to. It’s important to understand that, in python, the methoddefline (not the body, obviously), is only run once, not every time you create a new instance (or run the function, for that matter).Here’s a corrected version. Instead of defaulting to
[], you should most always default toNonethen handle setting it as a list of nothing was given.Now this prints as expected: