Skip to content
Advertisement

Is it possible to create nested class attributes?

I’m pretty new to Python and have recently learned about classes. I’ve been experimenting around with them and have come up with a student/course grading system. Here’s the code so far:

JavaScript

So this creates a course class, which I can add students to and set their rooms and other stuff. I’ve got another class, which is intended to store information on students:

JavaScript

Pretty simple; I’ve just been stuck on how to create the actual grading system. If I were to do:

JavaScript

Would it be possible to then use “nested attributes”? So I’d assign that student’s grade of a course to a value like:

JavaScript

This however doesn’t work, and throws an (expected) AttributeError. So would I have to use my previously created course_list?

JavaScript

Even then I’m not sure how I’d assign grade to that course object.

Advertisement

Answer

Here’s a solution that addresses some of the above issues by assigning a “course slot” to a student, rather than the course itself. As you might imagine, there is a limit to the number of course slots available which depends on the course max size. The code can be developed a lot further, but I thought this could be good to get you started:

JavaScript

Example usage

Instantiate courses:

JavaScript

Instantiate student 1 and assign a course slot:

JavaScript

Instantiate student 2 and assign a course slot

JavaScript

Get course info:

JavaScript

I guess the cheat is that the course student_list only gets the name of the student and not the Student object, which could probably work if you pass it a unique ID and then iterate through a list of Student objects to match on ID. Something to think about anyway.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement