0
0
Pythonprogramming~30 mins

Inheriting attributes and methods in Python - Mini Project: Build & Apply

Choose your learning style9 modes available
Inheriting attributes and methods
📖 Scenario: Imagine you are creating a simple program to manage different types of vehicles. All vehicles share some common features like having a brand and a method to describe themselves. But specific types of vehicles, like cars, have extra features.
🎯 Goal: You will build a base class called Vehicle with common attributes and methods. Then, you will create a subclass called Car that inherits from Vehicle and adds its own attribute. Finally, you will create an object of Car and print its description.
📋 What You'll Learn
Create a class called Vehicle with an __init__ method that takes brand as a parameter and stores it.
Add a method called describe in Vehicle that returns a string describing the vehicle brand.
Create a subclass called Car that inherits from Vehicle.
Add an __init__ method to Car that takes brand and model, calls the parent __init__, and stores model.
Override the describe method in Car to include both brand and model in the description.
Create an object of Car with brand "Toyota" and model "Corolla".
Print the description of the car object.
💡 Why This Matters
🌍 Real World
Inheritance helps organize code when many objects share common features but also have unique parts. For example, different types of vehicles share some traits but also have their own details.
💼 Career
Understanding inheritance is important for writing clean, reusable code in many programming jobs, especially in software development and object-oriented programming.
Progress0 / 4 steps
1
Create the base class Vehicle
Create a class called Vehicle with an __init__ method that takes a parameter brand and stores it in self.brand. Also, add a method called describe that returns the string "This vehicle is a {self.brand}" using an f-string.
Python
Need a hint?

Remember to use self.brand = brand inside __init__ and return the description string with an f-string.

2
Create the subclass Car with extra attribute
Create a subclass called Car that inherits from Vehicle. Add an __init__ method that takes parameters brand and model. Inside it, call the parent __init__ with brand and store model in self.model.
Python
Need a hint?

Use super().__init__(brand) to call the parent class constructor.

3
Override the describe method in Car
In the Car class, override the describe method to return the string "This car is a {self.brand} {self.model}" using an f-string.
Python
Need a hint?

Make sure the describe method is inside the Car class and returns the correct string.

4
Create a Car object and print description
Create an object called my_car of class Car with brand "Toyota" and model "Corolla". Then, print the result of calling my_car.describe().
Python
Need a hint?

Make sure to create my_car with the correct brand and model, then print my_car.describe().