Here’s an example of a Car
class that meets the requirements outlined in your prompt:
class Car:
def __init__(self, make: str, model: str, year: int, speed: float):
"""Initialize the car's make, model, year, and speed."""
self.make = make # string
self.model = model # string
self.year = year # integer
self.speed = speed # float
def accelerate(self, increase: float):
"""Increase the speed of the car by the given amount."""
self.speed += increase
print(f"{self.make} {self.model} is now going {self.speed} mph.")
def brake(self, decrease: float):
"""Decrease the speed of the car by the given amount."""
self.speed -= decrease
if self.speed < 0:
self.speed = 0
print(f"{self.make} {self.model} is now going {self.speed} mph.")
def get_speed(self) -> float:
"""Return the current speed of the car."""
return self.speed
def display_info(self):
"""Print the information of the car."""
print(f"Car Make: {self.make}, Model: {self.model}, Year: {self.year}, Speed: {self.speed} mph")
def __eq__(self, other):
"""Check if two cars are the same based on their make and model."""
return self.make == other.make and self.model == other.model
# Instantiate three different Car objects
car1 = Car("Toyota", "Camry", 2020, 50.0)
car2 = Car("Honda", "Civic", 2021, 30.0)
car3 = Car("Toyota", "Camry", 2020, 50.0)
# Testing the eq method
if car1 == car3:
print("car1 and car3 are the same car.")
else:
print("car1 and car3 are different cars.")
# Using methods of the Car class
car1.accelerate(10) # Increases speed by 10
car2.brake(5) # Decreases speed by 5
# Display car information
car1.display_info()
car2.display_info()
Breakdown of the Car
Class:
-
Attributes:
make
(string): The make of the car (e.g., "Toyota").model
(string): The model of the car (e.g., "Camry").year
(integer): The year of manufacture.speed
(float): The current speed of the car.
-
Methods:
accelerate
: Increases the car's speed.brake
: Decreases the car's speed.get_speed
: Returns the current speed of the car (returns a value).display_info
: Prints out the car’s attributes in a readable format (does not return a value).__eq__
: Compares twoCar
objects based on theirmake
andmodel
.
-
Usage:
- Three
Car
objects are instantiated:car1
,car2
, andcar3
. - The
eq
method is tested betweencar1
andcar3
. - Various methods are called on the objects to demonstrate their functionality.
- Three
This implementation covers the requirements you specified, including data types, methods with and without parameters, and returns, as well as a demonstration of object equality.