Here's an implementation of the Car
class according to the specified requirements. This class includes instance attributes, various methods, and uses different data types. I'll also provide an example of creating instances of the Car
class and testing the equality method.
class Car:
def __init__(self, make: str, model: str, year: int, speed: float):
self.make = make # The make of the car (string)
self.model = model # The model of the car (string)
self.year = year # The year of manufacture (integer)
self.speed = speed # The speed of the car (float, in km/h)
def accelerate(self, increase: float):
"""Increases the speed of the car by a specified amount."""
self.speed += increase
print(f"The speed of the {self.make} {self.model} has increased to {self.speed} km/h.")
def brake(self, decrease: float):
"""Decreases the speed of the car by a specified amount."""
if self.speed - decrease < 0:
self.speed = 0
else:
self.speed -= decrease
print(f"The speed of the {self.make} {self.model} has decreased to {self.speed} km/h.")
def get_speed(self) -> float:
"""Returns the current speed of the car."""
return self.speed
def display_info(self):
"""Displays information about the car."""
print(f"{self.year} {self.make} {self.model}, Speed: {self.speed} km/h")
def __eq__(self, other):
"""Compares two Car objects based on their make and model."""
if isinstance(other, Car):
return self.make == other.make and self.model == other.model
return False
# Instantiating different Car objects
car1 = Car("Toyota", "Corolla", 2020, 80.0)
car2 = Car("Honda", "Civic", 2019, 70.0)
car3 = Car("Toyota", "Corolla", 2020, 90.0)
# Using methods from the class
car1.accelerate(20) # Increase speed
car1.brake(10) # Decrease speed
print(car1.get_speed()) # Get the current speed
car1.display_info() # Display car information
# Testing the equality method
print(car1 == car2) # Should print False
print(car1 == car3) # Should print True
# Output information about the first car
print("First Car Info:")
car1.display_info()
Breakdown of the Class:
- Attributes:
make
,model
,year
, andspeed
represent the properties of the cars. - Methods:
accelerate(increase)
: Increases speed and prints the new speed.brake(decrease)
: Decreases speed and checks to ensure it doesn't go below 0.get_speed()
: Returns the current speed of the car.display_info()
: Prints detailed information about the car.
- Equality Method:
__eq__
compares two car objects based onmake
andmodel
. - Instantiation: Three different car instances are created to demonstrate the functionality.
You can run this code in your Python environment to test its functionality. If you need to submit your work through PythonAnywhere, you can copy and paste this code into your Python editor there.