Here's a Python class that fulfills your requirements. The class is named Car
and includes various attributes, methods, and instantiates three different car objects.
class Car:
def __init__(self, make: str, model: str, year: int, speed: float):
self.make = make # string
self.model = model # string
self.year = year # integer
self.speed = speed # float
def accelerate(self, increase: float):
"""Increases the speed of the car."""
self.speed += increase
def brake(self, decrease: float):
"""Decreases the speed of the car if it's above 0."""
if self.speed - decrease >= 0:
self.speed -= decrease
else:
self.speed = 0
def get_speed(self) -> float:
"""Returns the current speed of the car."""
return self.speed
def __eq__(self, other):
"""Comparing two Car objects based on their make, model, and year."""
if isinstance(other, Car):
return (self.make == other.make and
self.model == other.model and
self.year == other.year)
return False
def display_info(self):
"""Displays information about the car."""
print(f"Car Make: {self.make}, Model: {self.model}, Year: {self.year}, Speed: {self.speed} km/h")
# Instantiating Car objects
car1 = Car("Toyota", "Corolla", 2020, 0)
car2 = Car("Toyota", "Corolla", 2020, 50)
car3 = Car("Honda", "Civic", 2021, 30)
# Test the accelerate and brake methods
car1.accelerate(60) # car1 accelerates to 60 km/h
car2.brake(20) # car2 slows down to 30 km/h
# Print information about car1
car1.display_info()
# Compare car1 and car2 using the eq method
if car1 == car2:
print("car1 and car2 are the same.")
else:
print("car1 and car2 are different.")
# Compare car2 and car3 using the eq method
if car2 == car3:
print("car2 and car3 are the same.")
else:
print("car2 and car3 are different.")
Explanation:
- Instance Attributes: The
Car
class has four instance attributes:make
(str),model
(str),year
(int), andspeed
(float). - Methods:
accelerate
(increases speed and does not return a value).brake
(decreases speed, checks for non-negative value, does not return a value).get_speed
(returns the current speed).__eq__
(compares twoCar
objects based on make, model, and year).display_info
(prints the car's information).
- Instantiating Objects: Three
Car
objects (car1
,car2
,car3
) are created. - Method Calls: The program demonstrates the use of methods on the car objects, including speed adjustment and information display.
- Equality Comparison: It checks whether
car1
is equal tocar2
and whethercar2
is equal tocar3
, printing appropriate messages based on the comparisons.