First of all apologies for the terrible title, but I couldn't find a better description.
Let's describe my problem using an example:
I have two classes: Homework and Student
class Homework:
def __init__(self, name):
self.name = name
def execute(self):
print(f"Hello. I'm the {self.name} homework and my execution is long and tedious")
result = 0
return result
class Student:
def __init__(self, homework):
self.homework = homework
def do_homework(self):
return self.homework.execute()
Each student is assigned an homework from a list, where the number of available homeworks is much smaller than the number of students (something like 2 homeworks for 300 students).
math = Homework('math')
chemistry = Homework('chemistry')
all_students = [Student(math) for _ in range(5)]
all_students += [Student(chemistry) for _ in range(5)]
I'd like to call the method do_homework for each student and collect the outputs in a list.
output = [st.do_homework() for st in all_students]
This will call the method execute of their assigned homework. However, since the execution of the homework is long and tedious, I'd like the execute method of each homework type to be executed only once and then the output repeated in the output list depending on the order of the students in all_students.
One trivial solution could be to have a dict of Homeworks and create a dict of results out of it. Then each student should point **not to the Homework object itself, but rather the key of that homework in the dict of Homeworks*.
I find this latter solution a bit fragile due to the indirect link between the students and the homework only relying on the comparison of the two keys.
Is it possible to achieve the same result, keeping the reference to the Homework inside the Student? Any smart idea?
PS: just to provide a context to the curious among you, the "students" in my code are structural elements, each of which can be of a different material (the "homework"). During the execution I set a temperature and I want to run a method whose output only depends on the material of the element. Therefore all the elements of the same material will output the same value. However this calculation is "long" and repeating it thousands of time for each element is a waste of time, since I only have a handful of materials. Hence my question