Below is an example of a Car
class with the specified requirements. The class has instance attributes, methods, and demonstrates the use of different data types.
class Car:
def __init__(self, make: str, model: str, year: int, speed: float):
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 by increment."""
self.speed += increment
print(f"The speed of the {self.make} {self.model} has increased to {self.speed} mph.")
def brake(self, decrement: float) -> None:
"""Reduce the speed of the car by decrement."""
self.speed = max(0, self.speed - decrement)
print(f"The speed of the {self.make} {self.model} has decreased to {self.speed} mph.")
def get_description(self) -> str:
"""Return a string description of the car."""
return f"{self.year} {self.make} {self.model} moving at {self.speed} mph."
def is_faster_than(self, other_car: 'Car') -> bool:
"""Compare the speed of two cars."""
return self.speed > other_car.speed
def __eq__(self, other: 'Car') -> bool:
"""Check if two cars are the same model and make."""
return self.make == other.make and self.model == other.model
# Instantiate three different Car objects
car1 = Car("Toyota", "Camry", 2020, 60.0)
car2 = Car("Honda", "Civic", 2019, 55.0)
car3 = Car("Toyota", "Camry", 2020, 60.0)
# Test the eq method
print(car1 == car2) # Should print False
print(car1 == car3) # Should print True
# Use other methods
car1.accelerate(10) # Increase speed of car1
car2.brake(20) # Decrease speed of car2
print(car1.get_description()) # Print description of car1
print(car2.get_description()) # Print description of car2
# Check which car is faster
if car1.is_faster_than(car2):
print(f"{car1.make} {car1.model} is faster than {car2.make} {car2.model}.")
else:
print(f"{car2.make} {car2.model} is faster than {car1.make} {car1.model}.")
Explanation:
-
Attributes:
make
: Car manufacturer's name (string).model
: Car model name (string).year
: Year of manufacture (integer).speed
: Current speed of the car (float).
-
Methods:
accelerate
: Increases the car's speed (does not return a value).brake
: Decreases the car's speed (does not return a value).get_description
: Returns a description of the car (returns a string).is_faster_than
: Compares the speed of two Car objects (takes another car as a parameter and returns a boolean).__eq__
: Overrides the equality operator to compare if two car objects are the same based on make and model.
-
Instantiating Objects:
- Three Car objects are instantiated, with comparisons performed using the equality method.
- Print statements provide information about the objects and validate the functionalities tested.
This design meets all outlined requirements and demonstrates the principles of object-oriented programming in Python.