I am in the situation where I need a class that is within another (as an attribute) to communicate with the class that contains it, however, I cannot wrap my head around how to do it.
Take this situation as an example: There is a class HighSchoolClass that contains a list of Students that belong to that class, and HighSchoolClass has a method foo rearranging how the students are sited or whatever. But then, each student has the capability of asking if a rearranging can be made. So it would need to call the method for rearranging the class.
# Singelton
class HighSchoolClass:
def __init__(self):
self.list_of_students = # A list of instances of Student
self.profesor = ...
def rearrange_class():
# do something
class Student:
def ask_for_rearrange():
# Needs to call rearrange_class() of the class he is in.
Is there any way of do this (ideally just calling it somehow)? Mind that rearrange_class() is not static. If it helps, the HighSchoolClass would be a singelton.
CodePudding user response:
Typically, you would explicitly give each Student
a reference to the HighSchoolClass
that they belong to. A simple example might look like
class Student:
def __init__(self):
self.class_ = None
def add_class(self, class_):
self.class_ = class_
class HighSchoolClass:
def __init__(self):
self.list_of_students = []
def add_student(self, student):
self.list_of_students.append(student)
class Registrar:
def add_student_to_class(self, student, class_):
class_.add_student(student)
student.add_class(class_)
Note the use of a third class to both the student and the class. Otherwise, it's not obvious whether a student should be responsible for updating each class they join, or whether each class should update their students.
the_class = HighSchoolClass()
s1 = Student()
s2 = Student()
r = Registrar()
r.add_student_to_class(s1, the_class)
r.add_student_to_class(s2, the_class)
Now, each class and student has a reference to the other to be used as needed.