Here's a Python implementation of the Car
class that meets your requirements:
class Car:
def __init__(self, make: str, model: str, year: int, speed: float = 0.0):
self.make = make # type: str
self.model = model # type: str
self.year = year # type: int
self.speed = speed # type: float
def accelerate(self, increment: float) -> None:
"""Increase the speed of the car."""
self.speed += increment
print(f"The speed has been increased to {self.speed} mph.")
def brake(self, decrement: float) -> None:
"""Decrease the speed of the car."""
self.speed = max(0, self.speed - decrement)
print(f"The speed has been decreased to {self.speed} mph.")
def get_speed(self) -> float:
"""Return the current speed of the car."""
return self.speed
def __eq__(self, other: object) -> bool:
"""Compare two Car objects based on make and model."""
if not isinstance(other, Car):
return NotImplemented
return self.make == other.make and self.model == other.model
def car_info(self) -> str:
"""Return a string with information about the car."""
return f"{self.year} {self.make} {self.model}, Speed: {self.speed} mph"
# Instantiate three different Car objects
car1 = Car("Toyota", "Camry", 2020)
car2 = Car("Honda", "Civic", 2021)
car3 = Car("Toyota", "Camry", 2020, 50.0)
# Test the accelerate and brake methods
car1.accelerate(30)
car1.brake(10)
print(car1.car_info())
# Test getting the speed
current_speed = car1.get_speed()
print(f"Current speed of {car1.make} {car1.model} is {current_speed} mph.")
# Test the __eq__ method
print(f"Car 1 and Car 2 are equal: {car1 == car2}")
print(f"Car 1 and Car 3 are equal: {car1 == car3}")
Explanation:
-
Attributes: The
Car
class has four instance attributes:make
(string),model
(string),year
(integer), andspeed
(float). -
Methods:
accelerate(increment)
: Increases the speed of the car and prints the new speed (does not return a value).brake(decrement)
: Decreases the speed of the car and prints the new speed (does not return a value).get_speed()
: Returns the current speed of the car (returns a value).car_info()
: Provides a formatted string with information about the car (returns a value).__eq__(other)
: Compares two car objects based on theirmake
andmodel
.
-
Instantiation: Three
Car
objects (car1, car2, car3) are created with different attributes. -
Testing: The methods are tested through function calls, and the equality method is validated by comparing car1 with car2 and car3. A print statement provides information about one of the cars' speeds.