Objectification of Python Objects and Their Inheritance

whale image

In my last article I explained how to set up a Python class with some basic parameters using the dunder methods, and a custom function to handle a student’s grade average.

Here I want to address the capabilities of Python class inheritance. Let’s say later on I want to start organizing the schools in my district. I can, like normal, create a school class object with its own set of properties. Let’s just say I want the school’s name, the state it’s in, the district, and the students that I’ve initiated with my StudentGpa class. Here’s how the class would look:

pretty normal, right?

Now how do I make this inherit the StudentGpa class? I’ll pass the initiated variables of my students as the students parameter. This time I’ll put them in a list for Baxter High and Sunny Dale.

You can see where I initiated the School class with baxter_high, and sunnydale_high. The last parameter passed was a list of initiated StudentGpa classes. There is a bit of juggling involved, so keeping things clear and using good naming convention is important! My School class now has access to whatever I have returning from my StudentGpa class.
From here I can create custom functions with the passed down information.

I created a find_student() function to tell me if a student was attending the school I had initiated.

To call it I used the initiated class (baxter_high) appended my neat new function (find_student()), and passed the initiated student from before with the StudentGpa class, and all my information is intermingling and accessible.
Now I’m sure if you looked closely at my snippets you’ll see ways the code can be made more streamline or easier to use, and there surely is. It’s important to think ahead.
Before I go I wanted to give another example of inheritance, and that is to pass information as a parameter in the class.

Exception is a unique built in Python function that handels errors. I made a class of it, and printed out the statement “Student not found” as a custom error handler. I then passed StudentError into School as a parameter, and returned it in my find_student() function. It’s nice to have this ability, and to be able to customized my error messages, so that my errors could be easier to find. This would be immensely helpful if I’m working in a large file.
I hope this article brought some better understanding of Python Classes.