Menu

Sign in to track your progress and unlock all features.

Theme style

Log in
01. Implement Base and Derived ClassesE02. Override a Method in a SubclassE03. Use super() to Call Parent __init__E

Problem No 1

Implement Base and Derived Classes

Easy

8 minute session

Summary

Create a base class and extend it with derived classes that add attributes and override behavior.

Problem statement

You will implement a simple class hierarchy. Create a Vehicle base class with make, model, and year attributes. Implement methods: - description(): returns a string in the format "{year} {make} {model}". - age(current_year): returns the vehicle's age as an integer (current_year - year). Then implement two subclasses: - ElectricVehicle: adds battery_capacity (an integer representing kWh) and overrides description() to append " ({battery_capacity} kWh)" to the base description. - Motorcycle: adds has_sidecar (boolean, default False) and overrides description() to append " with sidecar" if has_sidecar is True, otherwise return the base description. Follow the starter code and fill in the TODOs. Return values are strings or integers as specified.

Task

Implement a Vehicle base class and two derived classes (ElectricVehicle and Motorcycle) that extend and override methods.

Examples

Electric vehicle description

Input

ElectricVehicle('Nissan','Leaf',2018,40).description()

Output

2018 Nissan Leaf (40 kWh)

Explanation

The ElectricVehicle description includes the base description plus the battery capacity in kWh.

Input format

A class-based API. Tests will instantiate classes and call methods, e.g. Vehicle('Toyota','Corolla',2010).description()

Output format

Methods should return strings or integers. The test harness evaluates expressions and compares their string form.

Constraints

- Use standard Python classes. - Do not print; methods must return values. - year and battery_capacity are integers. has_sidecar is a boolean.

Samples

Sample input 0

Motorcycle('Harley','Sportster',2015,True).description()

Sample output 0

2015 Harley Sportster with sidecar

Explanation 0

Motorcycle adds a sidecar indicator and appends the phrase when True.

Code editor
Loading editor…

AI assistant

Ask me anything!

Need help? I can explain the core idea behind this problem, review your current code, and give targeted hints. Use “Teach Theory” for the concept, “Get AI hint” for a quick scaffold nudge, or ask a specific question below.

Chat history is temporary and will not be saved.

03:43 PM

Free preview includes 1 Teach Theory response and 1 AI hint on each of the first 3 lessons in this module.