Technical Tuesday: Coding Challenge Walkthrough
Today I’ll do another coding challenge from my Python learning journey. This coding challenge was to reinforce what I learned about inheritance and OOP programming.
- 1 class named Computer
- 2 sub classes named Desktop and Laptop that inherit from Computer
- Computer must have 2 methods: getspecs and displayspecs
- Desktop and Laptop muse have one spec exclusive to them (ex: size, weight, etc)
-Subclasses must have their own methods to get and display their unique spec
- Create an object of laptop or desktop and make sure to call all the methods from Computer class and their own class.
Time to get on it!
Starting with the class Computer, I want to have 3 methods total. One to initialize my variables, along with the methods getspecs() and displayspecs(). I’ll use Ram and Processor as my specs.
Once I have those variables established, I want to start working on the two methods required in this challenge. getspecs() will use the input of the user to gather the information so I want to use the input(prompt) format to get and save the data to each variable as such:
For displayspecs() I’ll simply grab that information and print the data we have.
Now to see if it works, I’ll call on my methods as such:
This will prompt the user to input our spec info and then display it and it looks like this in my console.
Now for my subclasses Desktop and Laptop, the format will be similar save for how I call on our inherited class when setting up the subclasses. When I create my subclasses, I need to format it as such:
This format lets Python know that Desktop will inherit data and methods from the Computer class. When I’m done creating Desktop and Laptop with whatever specs I want (I used Monitors for Desktop and Size for Laptop) it came out like this:
Now, I have most of it done! After creating the Computer class it is simply copy, paste, and tweak for Desktop and Laptop because I try to work smarter not harder here. I’ve checked off everything except for my objects, so let’s get to that.
I want to create an object for Desktop or Laptop. I chose Laptop because why not?
But now what? I call on not only my inherited methods but Laptop’s methods as well per the challenge requirements.
We should get a prompt in our console to input our information and once given, should display the information just like this.
And that’s it! A simple walkthrough for a coding challenge for Inheritance and object oriented programming.